How do I populate a JComboBox with an ArrayList?
Use the toArray()
method of the ArrayList class and pass it into the constructor of the JComboBox
See the JavaDoc and tutorial for more info.
Elegant way to fill combo box with an array list :
List<String> ls = new ArrayList<String>();
jComboBox.setModel(new DefaultComboBoxModel<String>(ls.toArray(new String[0])));
I don't like the accepted answer or @fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.
String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);
Alternatively, you can also maintain strong typing by just using a for loop.
String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);