miqbal
miqbal

Reputation: 2227

Create Swing component from string

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

Upvotes: 1

Views: 1717

Answers (3)

Óscar López
Óscar López

Reputation: 236170

It can be done, using the Reflection API:

Class<?> klazz = Class.forName("javax.swing.JPanel");
JPanel panel = (JPanel) klazz.newInstance();

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 to Class<?> 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:

Object obj = klazz.newInstance();

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 Constructor object first before instantiating the new object:

Class<?> klazz = Class.forName("javax.swing.JPanel");
Constructor<?> constructor = klazz.getDeclaredConstructor(/* parameter types */);
JPanel panel = (JPanel) constructor.newInstance();

Upvotes: 3

Reimeus
Reimeus

Reputation: 159874

You could use reflection:

// c is JPanel for instance
Sting componentClassName = "javax.swing." + c; 
JPanel panel = (JPanel)Class.forName(componentClassName).newInstance();

Using Class.newInstance() requires a the component you are creating to have a default constructor but this is provided by most if not all the standard Swing components.

Upvotes: 2

Aniket Inge
Aniket Inge

Reputation: 25733

see here How to create an object from a string in java how to eval a string and Creating an instance from string in java. But I would also suggest you to write your own preprocessor if you want it to evaluate in 1 single line. That's what C/C++ preprocessors do.

Upvotes: 0

Related Questions