Is it possible to instantiate an object whose type is set in a JComboBox at runtime?
Let's say I have an abstract class Fruits
.
I have classes Apple
and Banana
extending Fruits
.
There is a reference to an object that is gonna instantiated at runtime: Fruits chosenFruit
I want to do something like this:
Fruits chosenFruit;
JComboBox<Fruits> combo = new JComboBox<Fruits>();
Apple appleCombo = new Apple();
Banana bananaCombo = new Banana();
combo.add(appleCombo );
combo.add(bananaCombo);
// When user chose a fruit in JComboBox and clicked OK:
chosenFruit = new combo.getSelectedItem().getClass(); // or .getType() ???
The problem here is, that I instantiated two objects (appleCombo and bananaCombo) only to add them to the JComboBox. But I want only the type of the new object to get displayed in JComboBox and to get set by the user. I hope this is reasonable.
Thanks in advance!
Edit: So, is there a way to do something like this:
JComboBox<Class> combo = new JComboBox<Class>();
combo.add(Apple);
combo.add(Banana);
Fruits chosenFruit = new combo.getSelectedItem();