
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we sort the items of a JComboBox in Java?
In this article, we will learn to sort the items of a JComboBox in Java. A JComboBox is a basic Swing component, and one of its common requirements is to show the items in sorted order.
What is a JComboBox?
A JComboBox is a subclass of the JComponent class, and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate the ActionListener, ChangeListener, and ItemListener interfaces when the user actions with a combo box.
Syntax
The following is the syntax for JComboBox initialization:
JComboBox comboBox = new JComboBox(model);
By default, a JComboBox does not support sorting the items. We can customize the code by extending the DefaultComboBoxModel class.
Different Approaches
The following are the two different approaches to sort the items of a JComboBox in Java:
Custom ComboBox Model
This method generates a customized DefaultComboBoxModel subclass that sorts items automatically upon insertion. It handles sorting internally and maintains the order dynamically.
Approach
The following are the steps of sorting the items in a JComboBox using the custom ComboBox Model:
-
SortedComboBoxModel inherits from DefaultComboBoxModel:
- Constructor with array or vector: Sorts elements first via Arrays.sort() method, or Collections.sort() method and places them in order.
- It uses an overridden addElement() and insertElementAt(), which ensure that every new element added will be included in the correct sorted index by Comparable.compareTo().
- JTextField accepts text and, upon pressing Enter, a name is added and inserted in ascending order.
- UI is built using BoxLayout for a neat layout with a label, input, and a combobox.
- The setPrototypeDisplayValue() method offers a consistent width for the dropdown.
A constructor that takes an array of items and sorts the array items using the sort() method:
public SortedComboBoxModel(Object[] items) { Arrays.sort(items);
Adds sorted items to the model:
for (Object item : items) { super.addElement(item); }
Example
Below is an example for sorting the items in a JComboBox using the custom ComboBox Model:
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class JComboBoxSorterTest extends JFrame { private JComboBox comboBox; private JTextField textField; public JComboBoxSorterTest() { setTitle("JComboBoxSorter Test"); setLayout(new FlowLayout()); textField = new JTextField(10); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { comboBox.addItem(textField.getText()); textField.setText(""); comboBox.showPopup(); } }); String[] items = {"raja", "archana", "vineet", "surya", "krishna", "jai", "adithya"}; SortedComboBoxModel model = new SortedComboBoxModel(items); comboBox = new JComboBox(model); comboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); Box box1 = Box.createHorizontalBox(); box1.add(new JLabel("Enter a name and hit enter ")); box1.add(textField); Box box2 = Box.createHorizontalBox(); box2.add(comboBox); add(box1); add(box2); setSize(375, 250); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } // Customize the code for sorting of items in the JComboBox private class SortedComboBoxModel extends DefaultComboBoxModel { public SortedComboBoxModel() { super(); } public SortedComboBoxModel(Object[] 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 items) { Collections.sort(items); int size = items.size(); for (int i = 0; i < size; i++) { super.addElement(items.elementAt(i)); } setSelectedItem(items.elementAt(0)); } public void addElement(Object element) { insertElementAt(element, 0); } public void insertElementAt(Object 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); } } public static void main(String[] args) { new JComboBoxSorterTest(); } }
Output
Using a Wrapper ListModel
This approach uses a standard DefaultComboBoxModel, but manually sorts its contents using a helper method sortModel() each time a new item is added.
Approach
The following are the steps of sorting the items in a JComboBox using a Wrapper ListModel:
- It creates a default combobox model from an array.
- The sortModel() function:
- Copies all elements into a List.
- Sorts them using Collections.sort() and String.CASE_INSENSITIVE_ORDER.
- JTextField input adds new items to the model and subsequently calls sortModel() to order them.
- Clears and refills the model in sorted order.
Get all elements from the model:
List items = new ArrayList<>(); for (int i = 0; i < model.getSize(); i++) { items.add(model.getElementAt(i)); }
Sort the list using the sort() method from the Collections:
Collections.sort(items, String.CASE_INSENSITIVE_ORDER);
Example
Below is an example for sorting the items in a JComboBox using the wrapper ListModel:
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class JComboBoxSorterAlternative extends JFrame { private JComboBox<String> comboBox; private JTextField textField; private DefaultComboBoxModel<String> model; public JComboBoxSorterAlternative() { setTitle("Alternative JComboBox Sorter"); setLayout(new FlowLayout()); textField = new JTextField(10); textField.addActionListener(e -> { model.addElement(textField.getText()); sortModel(); textField.setText(""); comboBox.showPopup(); }); String[] items = {"raja", "archana", "vineet", "krishna", "adithya"}; model = new DefaultComboBoxModel<>(items); sortModel(); // Initial sort comboBox = new JComboBox<>(model); comboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); Box box1 = Box.createHorizontalBox(); box1.add(new JLabel("Enter a name and hit enter ")); box1.add(textField); Box box2 = Box.createHorizontalBox(); box2.add(comboBox); add(box1); add(box2); setSize(375, 250); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } private void sortModel() { List<String> items = new ArrayList<>(); for (int i = 0; i < model.getSize(); i++) { items.add(model.getElementAt(i)); } Collections.sort(items, String.CASE_INSENSITIVE_ORDER); model.removeAllElements(); for (String item : items) { model.addElement(item); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new JComboBoxSorterAlternative()); } }