问题
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