O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Combo Boxes

A combo box component is actually a combination of a Swing list (embedded in a pop-up window) and a text field. Because combo boxes contain a list, many of the classes discussed in the first part of this chapter are used here as well. Unlike lists, a combo box allows the user only one selection at a time, which is usually copied into an editable component at the top, such as a text field. The user can also manually enter a selection (which does not need to be on the list). Figure 7-10 shows a high-level class diagram for Swing’s combo box classes.

Swing combo box class diagram

Figure 7-10. Swing combo box class diagram

Like lists, the combo box component uses a data model to track its list data; the model is called ComboBoxModel.

The ComboBoxModel Interface

The ComboBoxModel interface extends the ListModel interface and is used as the primary model for combo box data. It adds two methods to the interface, setSelectedItem( ) and getSelectedItem( ), thus eliminating the need for a separate selection model. Since a JComboBox allows only one selected item at a time, the selection “model” is trivial and is collapsed into these two methods.

Because the data of the ComboBoxModel is stored in an internal list, the ComboBoxModel also reuses the ListDataEvent to report changes in the model state. However, with the addition of methods to monitor the current selection, the model is now obligated to report changes ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required