Menu Bar Selection Models
In all GUI environments, menu components allow only one
selection to be made at a time. Swing is no exception. Swing provides a
data model that menu bars and menus can use to emulate this behavior:
the SingleSelectionModel.
The SingleSelectionModel Interface
Objects implementing the SingleSelectionModel
interface do exactly what its name suggests: they maintain an array of
possible selections and allow one element in the array to be chosen at
a time. The model holds the index of the selected element. If a new
element is chosen, the model resets the index representing the chosen
element and fires a ChangeEvent to
each of the registered listeners.
Properties
Objects implementing the SingleSelectionModel interface contain the
properties shown in Table
14-1. The selected
property is a boolean that tells
if there is a selection. The selectedIndex property is an integer index that represents the
currently selected item.
Table 14-1. SingleSelectionModel properties
Property | Data type | get | is | set | Default value |
|---|---|---|---|---|---|
| boolean | · | |||
selectedIndex | int | · | · |
Events
Objects implementing the SingleSelectionModel interface must fire a
ChangeEvent (not a PropertyChangeEvent) when the object
modifies its selectedIndex
property, i.e., when the selection has changed. The interface
contains the standard addChangeListener(
) and removeChangeListener(
) methods for maintaining a list of ChangeEvent listeners.
- void addChangeListener(ChangeListener listener)void removeChangeListener(ChangeListener ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access