我有一个由多个类实现的接口(interface)。我想创建一个包含所有类的 JComboBox,使用对象本身作为项目。
这就是我现在为每个类使用一行的内容:
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
当您在 JComboBox 上调用 getSelectedItem()
时,它将返回该对象,并且该对象将被添加到接口(interface)类型的列表中。有没有办法通过循环遍历类列表来完成此操作,而不是显式实例化每个对象?
最佳答案
Is there a way to do this with a loop through a list of classes instead of instantiating each object explicitly?
不确定这样做的意义是什么?您仍然需要:
- 创建列表
- 将类添加到列表
- 迭代列表,创建每个类的实例,然后将对象添加到组合框中。
这不会保存任何代码并使过程变得更加复杂。
无论如何,要回答您的基本问题,是的,您可以使用以下代码创建类的实例:
Class aClass = Car.class;
Car car = aClass.newInstance();
所以你可以使用类似的东西创建一个列表:
List<Class> items = new ArrayList<Class>();
items.add( Car.class );
items.add( Truck.class );
然后根据需要迭代列表。
关于java - 为列表中的 JComboBox 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47657520/