How can I create a Swing component ( such as a JPanel or JButton ) dynamically from a string that refers a component name?
For example;
String c = "JPanel";
(c) com = new (c)(); // It must be equivalent JPanel com = new JPanel();
or a function like this;
Object c = Object.createObjectFromString(c);
Thanks
It can be done, using the Reflection API:
Notice that you have to pass a fully-qualified class name to the
forName()method, and that at some point (be it as a type parameter toClass<?>or by using a cast like in the above code) you’ll have to explicitly specify the class that you intend to instantiate. Or if you don’t care about the exact type of the instance, you can simply do this:Also, I’m assuming that the class has defined a no-arguments constructor. If that is not the case, you’ll have to create a
Constructorobject first before instantiating the new object: