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.
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 ...
Get Java Swing, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.