Java Tips Weblog

  • Blog Stats

    • 115,201 hits
  • Categories

  • Archives

Sorted Combo Box Model

Posted by Rob Camick on November 11, 2008

A JComboBox displays the items in the drop down list in the order in which the items where added to the combo box. If you want the items sorted then you can use the Collections.sort() or Arrays.sort() methods on the data before you create the combo box model. But what if you have a dynamic combo box and you want to keep the items in sorted order as new items are added?

Well, then you can use 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.

When you create the combo box with code like the following…

String[] items = { "one", "two", "three" };
SortedComboBoxModel model = new SortedComboBoxModel(items);
JComboBox comboBox = new JComboBox( model );
comboBox.setSelectedItem("one");
comboBox.addItem("four");
comboBox.addItem("five");

… then the combo box will look like this when first displayed:

sorted-combo-box-model

Get The Code

SortedComboBoxModel.java

4 Responses to “Sorted Combo Box Model”

  1. Mouna said

    Very useful, thanks for sharing this!

  2. Sandwich said

    Are there any restrictions on the circulation of this code? Do you mind if I use it in a commercial project?

    • Rob Camick said

      As I stated on the About page:

      You are free to use and/or modify any or all code posted on the Java Tips Weblog without restriction. A credit in the code comments would be nice, but not in any way mandatory.

      Good luck with your project.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>