简体   繁体   中英

Create objects for a JComboBox in a list

I have an interface that is implemented by multiple classes. I want to create a JComboBox with all of the classes using the objects themselves as items.

This is kind of what I have now using a line for each class:

JComboBox<Vehicle> box = new JComboBox<>();
box.addItem(new Car());
box.addItem(new Truck());
box.addItem(new Plane());
// could be 5 more lines of object instantiation and adding

When you call getSelectedItem() on the JComboBox, it will return the object and that object will be added to a list of the interface type. Is there a way to do this with a loop through a list of classes instead of instantiating each object explicitly?

Is there a way to do this with a loop through a list of classes instead of instantiating each object explicitly?

Not sure what the point of this would be? You will still need to :

  1. create the List
  2. add the classes to the List
  3. iterate through the List, create an instance of each class and then add the object to the combo box.

This doesn't save any code and make the process more complicated.

In any case to answer your basic question yes, you can create an instance of a class using code like:

Class aClass = Car.class;
Car car = aClass.newInstance();

So you could create a List using something like:

List<Class> items = new ArrayList<Class>();
items.add( Car.class );
items.add( Truck.class );

Then you iterate through the List as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM