How to populate a JComboBox from an ArrayList?

放肆的年华 提交于 2020-01-17 14:48:12

问题


I've got an ArrayList of objects, and all the objects have names. How can I populate a JComboBox with those names? I've looked online and found nothing so far. There are some resources, but they tend to go with a hardcoded version, which is useless.

Since I don't have any code yet showing what I'm doing, I can't attach any.


回答1:


JComboBox works with Array or Vector. You should use .toArray() method in the ArrayList to create an array.

String[] names = namesList.toArray(new String[0]);

then use names




回答2:


You can directly feed in the items at construction time: JComboBox cb = new JComboBox(yourArrayList.toArray()); (you might have to check type parametrisation here)

JComboBox has constructors for Array and Vector as input. In your case it should be easier to convert to Array instead of converting to a Vector.

Or after initialization:

for (String item : yourArrayList) {
    cb.addItem(item);
}

See http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html



来源:https://stackoverflow.com/questions/25212020/how-to-populate-a-jcombobox-from-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!