The SortedComboBoxModel link from Alexis C. does not appear to work anymore, although the source link still works.
Nonetheless, I created a SortedComboBoxModel for classes that implement Comparable (based on this example).
public class SortedComboBoxModel<E extends Comparable<? super E>> extends DefaultComboBoxModel<E> {
public SortedComboBoxModel() {
super();
}
public SortedComboBoxModel(E[] items) {
Arrays.sort(items);
int size = items.length;
for (int i = 0; i < size; i++) {
super.addElement(items[i]);
}
setSelectedItem(items[0]);
}
public SortedComboBoxModel(Vector<E> items) {
Collections.sort(items);
int size = items.size();
for (int i = 0; i < size; i++) {
super.addElement(items.elementAt(i));
}
setSelectedItem(items.elementAt(0));
}
@Override
public void addElement(E element) {
insertElementAt(element, 0);
}
@Override
public void insertElementAt(E element, int index) {
int size = getSize();
for (index = 0; index < size; index++) {
Comparable c = (Comparable) getElementAt(index);
if (c.compareTo(element) > 0) {
break;
}
}
super.insertElementAt(element, index);
}
}
This can be used like so:
public static void main(String[] args) {
javax.swing.JComboBox<String> sortedComboBox = new javax.swing.JComboBox<>();
String[] testArray = new String[]{"DDD", "AAA", "CCC", "BBB"};
sortedComboBox.setModel(new SortedComboBoxModel<>(testArray));
//print out the sorted contents
for (int i = 0; i < sortedComboBox.getItemCount(); i++) {
System.out.println(i + ": " + sortedComboBox.getItemAt(i));
}
}