How to sort the jComboBox
elements list into sorted list.
JComboBox box=new JComboBox();
box.addItem(\"abc\");
box.addItem(\"zzz\");
box.addItem
You can have a look at the SortedComboBoxModel.
This model extends the DefaultComboBoxModel and has two additional pieces of functionality built into it:
- upon creation of the model, the supplied data will be sorted before
- the data is added to the model when adding new items to the model, the items will be inserted so as to maintain the sort order
The default sort order will be the natural sort order of the items added to the model. However, you can control this by specifying a custom Comparator as a parameter of the constructor.
Here's an example how to use it (taken from there):
String[] items = { "one", "two", "three" };
SortedComboBoxModel model = new SortedComboBoxModel(items);
JComboBox comboBox = new JComboBox(model);
comboBox.addItem("four");
comboBox.addItem("five");
comboBox.setSelectedItem("one");
Source code