Java: Sorting a JComboBox after adding an item

Patt

Diamond Member
Jan 30, 2000
5,288
2
81
I'm working on a basic application that allows the selection/removal of JComboBox items into a List object. When I remove an item from the List I add it back to the JComboBox, but it is appended onto the end, and I want it to sort itself alphabetically.

Is there a simple command I'm missing in the basic implementation of JComboBox to re-sort, or do I have to write something else that handles this situation?
 

PWNettle

Member
May 10, 2004
38
0
0
Your list object probably has an insert method that lets you insert at an index value, rather than adding (which sticks the item on the end of the list).

If so, you can loop on the list, comparing the text for the item you're inserting to the text of each item that's already in the list, and figure out where to insert to maintain alpha order without the need for a sort.
 

Cooler

Diamond Member
Mar 31, 2005
3,835
0
0
If you cant insert at an index you could store all elements in an arraylist and do a linar search for the postion of next element to insert . Then uses the arraylist to create a new JComboBox.
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Probably beyond the scope of your task, but you could subclass the DefaultComboBoxModel / implement ComboBoxModel to have it use a sorted collection.