Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components

How to Use Combo Boxes

A JComboBox(in the API reference documentation) comes in two forms: uneditable and editable. An uneditable combo box is surprisingly different from an editable one and should be considered separately.

A uneditable combo box is simply a popup menu: It allows the user to select a value from a menu of choices. Use an uneditable combo box instead of a group of radio buttons or a list to display one-of-many choices when space is limited, when the number of choices is large, or when the menu items are computed at run-time.

An editable JComboBox is a combination button, popup menu, and text field. The user can type in a value or choose the value from a menu. An editable combo box saves data-entry time by providing short-cuts to commonly entered values. See Using an Editable Combo Box for an example.

Here's a picture of an application that uses an uneditable combo box to let the user choose a pet picture from a popup menu:


Try this:
  1. Compile and run the program: ComboBoxDemo.java. You will also need 5 image files: Bird.gif, Cat.gif, Dog.gif, Rabbit.gif, and Pig.gif.
  2. Choose a pet from the combo box to view its picture.
  3. How to Use Radio Buttons provides a version of this program, RadioButtonDemo.java, that uses a group of radio buttons instead of a combo box. Compile and run that program. Compare the source code, operation, and UI of the two programs.

Below is the code from ComboBoxDemo.java that creates and sets up the combo box:
...
//in the ComboBoxDemo constructor
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

// Create the combo box, select the pig
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);
petList.addActionListener(this);
...
add(petList, BorderLayout.NORTH);
By default, a combo box is uneditable. The example doesn't call setEditable to change it, so the combo box created by this example is an uneditable combo box (basically a popup menu).

The code uses the JComboBox constructor that takes an array of objects. The objects used by this example are strings. However, the values can be any Object, in which case the Object's toString method provides the text to display. To put an image or other non-text value in the combo box's menu, you must provide a custom cell renderer with setRenderer.

A combo box uses a model object, specifically a ComboBoxModel(in the API reference documentation), to contain and manage the items in its menu. You can provide a combo box model object when you create a combo box, in which case the combo box initializes its menu from the items in the model, or you can provide it later with setModel. If you don't explicitly use a model, the combo box creates one implicitly and you can access it with getModel.

The code calls setSelectedIndex on the combo box to select the pig. Without this line of code the first item in the menu, Bird, would be selected at startup. Note that indices begin at 0.

The code also registers an action listener with the combo box. The listener's actionPerformed method is as follows:

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String petName = (String)cb.getSelectedItem();
    picture.setIcon(new ImageIcon("images/" + petName + ".gif"));
}
The method calls getSelectedItem to get the name of the pet chosen by the user, computes the path to the image, and loads the picture.


Warning: A combo box is a compound component: it consists of a button, a popup menu, and when editable, a text field. The combo box fires high-level events such as action events. Its subcomponents fire low-level events such as mouse, key, and focus events. Typically, for compound components such as the combo box, you should provide listeners for high-level events because the low-level events and the subcomponent that fires them are system-dependent. For information about events, including a discussion about high- and low-level events, refer to: Writing Event Listeners(in the Creating a User Interface trail).

Using an Editable Combo Box

Here's a picture of a demo application that uses an editable combo box to enter a pattern with which to format dates.


Try this:
  1. Compile and run the example: ComboBoxDemo2.java.
  2. Enter a new pattern by choosing one from the combo box's popup menu. The program reformats the current date and time.
  3. Enter a new pattern by typing one in and pressing Return. Again the program reformats the current date and time.

Below is the code from ComboBoxDemo2.java that creates and sets up the combo box:

String[] patternExamples = {
	 "dd MMMMM yyyy",
	 "dd.MM.yy",
	 "MM/dd/yy",
	 "yyyy.MM.dd G 'at' hh:mm:ss z",
	 "EEE, MMM d, ''yy",
	 "h:mm a",
	 "H:mm:ss:SSS",
	 "K:mm a,z",
	 "yyyy.MMMMM.dd GGG hh:mm aaa"
};
. . .
JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);
. . .
This code is very similar to the previous example, but warrants a few words of explanation. The bold line of code explicitly turns on editing to allow the user to type values in. This is necessary because, by default, a combo box is not editable. This particular example allows editing on the combo box because its menu does not provide all possible date formatting patterns.

The action listener for an editable combo box is called when the user chooses an item from the menu and when the user types Return in the text field.

The Combo Box API

The following tables list the commonly used JComboBox constructors and methods. Other methods you're likely to call are defined by the JComponent(in the API reference documentation) and Component(in the API reference documentation) classes and include [PENDING: anything in particular for JComboBox?]. [Link to JComponent and Component discussions.]

The API for using combo boxes falls into two categories:

Setting or Getting the Items in the Combo Boxes's Popup Menu
Method Purpose
JComboBox()
JComboBox(ComboBoxModel)
JComboBox(Object[])
JComboBox(Vector)
Create a combo box with the specified items in the popup menu. A combo box created with the default constructor has no items in the popup menu initially. Each of the other constructors initializes the popup menu from its argument: a model object, an array of objects, or a Vector of objects.
void addItem(Object)
void insertItemAt(Object, int)
Add or insert the specified object into the popup menu.
Object getItemAt(int)
Object getSelectedItem()
Get an item from the popup menu.
void removeAllItems()
void removeItemAt(int)
void removeItem(Object)
Remove one or more items from the popup menu.
int getItemCount() Get the number of items in the popup menu.
void setModel(ComboBoxModel)
ComboBoxModel getModel()
Set or get the data model that provides the items in the popup menu.

Customizing the Combo Box's Operation
Method Purpose
void addActionListener(ActionListener) Add an action listener to the combo box. The listener's actionPerformed method is called when the user selects an item from the combo box's menu or, in an editable combo box, when the user presses Return.
void setEditable(boolean)
boolean isEditable()
Set or get whether the user can type in the combo box.
void setRenderer(ListCellRenderer)
ListCellRenderer getRenderer()
Set or get the object responsible for painting the selected item in the combo box. The renderer is used only when the combo box is uneditable. If the combo box is editable, the editor is used to paint the selected item instead.
void setEditor(ComboBoxEditor)
ComboBoxEditor getEditor()
Set or get the object responsible for painting and editing the selected item in the combo box. The editor is used only when the combo box is editable. If the combo box is uneditable, the renderer is used to paint the selected item instead.

Examples that Use Combo Boxes

This table shows the examples that use JComboBox and where those examples are described.

Example Where Described Notes
ComboBoxDemo.java This page. An uneditable combo box.
ComboBoxDemo2.java This page. An editable combo box.
TableRenderDemo.java How to Use Tables Shows how to use a combo box as a table cell editor.


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components