That shows three combo boxes with each in two states:String[] bookTitles = new String[] {"Effective Java", "Head First Java",
"Thinking in Java", "Java for Dummies"};
JComboBox<String> bookList = new JComboBox<>(bookTitles);
// add to the parent container (e.g. a JFrame):
add(bookList);
// get the selected item:
String selectedBook = (String) bookList.getSelectedItem();
System.out.println("You seleted the book: " + selectedBook); That’s for a typical usage of the JComboBox component. Now let’s see other stuffs we can do with this component in details. JComboBox<String> myTitles = new JComboBox<String>(); JComboBox<Integer> myNumbers = new JComboBox<Integer>();
// create an empty combo box with items of type String
JComboBox<String> comboLanguage = new JComboBox<String>();
// add items to the combo box
comboLanguage.addItem("English");
comboLanguage.addItem("French");
comboLanguage.addItem("Spanish");
comboLanguage.addItem("Japanese");
comboLanguage.addItem("Chinese"); // define items in a String array:
String[] languages = new String[] {"English", "French", "Spanish", "Japanese", "Chinese"};
// create a combo box with the fixed array:
JComboBox<String> comboLanguage = new JComboBox<String>(languages); // define items in a vector collection:
Vector<String> languages = new Vector<String>();
languages.addElement("English");
languages.addElement("French");
languages.addElement("Spanish");
languages.addElement("Japanese");
languages.addElement("Chinese");
// create a combo box with the given vector
JComboBox<String> comboLanguage = new JComboBox<String>(languages); Generally a combo box can hold items of any type. If the type of the items is a custom object other than String, then the object’s toString() method will be used to get name of the items in the drop-down list. Following is an example that creates a combo box with items of a custom type Job:
JComboBox<Job> jobList = new JComboBox<Job>();
jobList.addItem(new Job("Developer"));
jobList.addItem(new Job("Designer"));
jobList.addItem(new Job("Architect"));
jobList.addItem(new Job("Team Leader")); The class Job is defined as follows:
class Job {
private String jobTitle;
public Job(String jobTitle) {
this.jobTitle = jobTitle;
}
public String toString() {
return this.jobTitle;
}
}Keep in mind that we have to override the toString() method to return a textual representation of the Job class, so the JComboBox class can use it to show item’s name in the drop-down list. // code to create a combo box as above... // make it editable myComboBox.setEditable(true);The following screenshot shows how an editable combo box looks like:
As we can see, the user can type “Spring framework” into the combo box as the drop-down list does not contain that title. class MyComboBoxModel extends DefaultComboBoxModel<Job> {
public MyComboBoxModel(Job[] items) {
super(items);
}
@Override
public Job getSelectedItem() {
Job selectedJob = (Job) super.getSelectedItem();
// do something with this job before returning...
return selectedJob;
}
}This custom model class, MyComboBoxModel extends the DefaultComboBoxModel class for the custom type Job, and overrides its getSelectedItem() method to control how a selected item would be returned. And we can pass an instance of this model class when creating a new JComboBox object as follows:Job[] jobs = new Job[] {
new Job("Developer"), new Job("Designer"), new Job("Tester")
};
MyComboBoxModel myModel = new MyComboBoxModel(jobs);
JComboBox<Job> jobList = new JComboBox<Job>(myModel);Or we can set the custom model for the combo box after it’s created like this:JComboBox<Job> jobList = new JComboBox<Job>(); jobList.setModel(myModel);
theFrame.setLayout(new FlowLayout()); theFrame.add(myComboBox);
thePanel.add(myComboBox, BorderLayout.CENTER);
thePanel.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); // set constraints details... constraints.gridx = 1; thePanel.add(myComboBox, constraints);
String[] bookTitles = new String[] {"Effective Java", "Head First Java", "Thinking in Java"};
JComboBox<String> bookList = new JComboBox<String>(bookTitles);
// add more books
bookList.addItem("Java Generics and Collections");
bookList.addItem("Beginnning Java 7");
bookList.addItem("Java I/O"); Job[] jobs = new Job[] {new Job("Developer"), new Job("Designer"), new Job("Tester")};
MyComboBoxModel myModel = new MyComboBoxModel(jobs);
myModel.addElement(new Job("Consultant"));
myModel.addElement(new Job("Manager"));
JComboBox<Job> jobList = new JComboBox<Job>(myModel); Note that the addItem() method of the JComboBox class still works in case of using a custom model.// remove an item of type String
bookList.removeItem("Thinking in Java");
// remove an item of a custom type Job
// the Job class must override the equals() method
Job consultantJob = new Job("Consultant");
jobList.removeItem(consultantJob);
// remove an item at a given index:
jobList.removeItemAt(2); bookList.removeAllItems();
// set selected item of type String:
bookList.setSelectedItem("Head First Java");
// set selected item of a custom type Job:
// the Job class must override the equals() method
Job consultantJob = new Job("Consultant");
jobList.setSelectedItem(consultantJob);
// set selected item at a given index:
jobList.setSelectedIndex(1); // get the selected item as an object String selectedBook = (String) bookList.getSelectedItem(); Job selectedJob = (Job) jobList.getSelectedItem(); // get the selected item as an index: int selectedIndex = jobList.getSelectedIndex();
// get the 4th item in the list String item4th = bookList.getItemAt(3);
// get total number of items: int totalBooks = bookList.getItemCount();
bookList.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JComboBox<String> combo = (JComboBox<String>) event.getSource();
String selectedBook = (String) combo.getSelectedItem();
if (selectedBook.equals("Effective Java")) {
System.out.println("Good choice!");
} else if (selectedBook.equals("Head First Java")) {
System.out.println("Nice pick, too!");
}
}
});The ActionEvent will be fired whenever an item is selected from the drop-down list, and perhaps this is the only useful action which we’re interested when working with JComboBox. bookList.setForeground(Color.BLUE);
bookList.setFont(new Font("Arial", Font.BOLD, 14)); And limit the maximum number of items displayed in the drop-down list:bookList.setMaximumRowCount(5);In this case, if the combo box contains more than 5 items, then the drop-down list will show only the first 5 ones and add a vertical scroll bar to navigating the rest items. This would be useful if we have a combo box with many items, thus such limitation is needed.Here’s the screenshot of a combo box whose appearance is customized as above:
See the tutorial Create custom GUI for JComboBox If you want to have a custom combo box looks like this:
It contains an editable combo box and two buttons. You can type new title into the combo box and hit Enter, and the new title will be added to the drop-down list. On clicking the Select button, a message dialog appears saying what is the selected book:
On clicking the Remove button, the currently selected item will be removed from the combo box. You can download full source code as well as executable JAR file of this program under the attachments section.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.