Combo Boxes

A combo box component is actually a combination of a Swing list (embedded in a popup window) and a text field. Because combo boxes contain a list inside of them, many of the classes you read about previously with lists are used here as well. Unlike lists, a combo box only allows the user one selection at a time, which is usually copied into an editable component at the top, such as a text field. The user can be permitted, however, to manually enter in a selection as well. 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. Recall that with a JComboBox there can be only one selected item at a time. Hence, what would be the selection model in lists 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 ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.