• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java: Sorting a JComboBox after adding an item

Patt

Diamond Member
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?
 
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.
 
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.
 
Probably beyond the scope of your task, but you could subclass the DefaultComboBoxModel / implement ComboBoxModel to have it use a sorted collection.
 
Back
Top