14.2 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.
14.2.1 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.
14.2.1.1 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
|
selected
|
boolean
|
|
·
|
|
|
selectedIndex
|
int
|
·
|
|
·
|
|
14.2.1.2 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 listener)
Add or remove the specified ChangeListener from the list of listeners receiving this model's change events.
14.2.1.3 Method
The SingleSelectionModel interface contains one other method:
- public void clearSelection( )
Clear the selection value, forcing the selected property to return false.
14.2.2 The DefaultSingleSelectionModel Class
Swing provides a simple default implementation of the SingleSelectionModel interface in the DefaultSingleSelectionModel class.
14.2.2.1 Properties
DefaultSingleSelectionModel contains just the properties required by the SingleSelectionModel interface, as shown in Table 14-2. The selectedIndex property is an integer index that represents the currently selected item. The default value of -1 indicates that there is no selection. The selected property is a boolean that returns true if the selectedIndex is anything other than -1, and false otherwise.
Table 14-2. DefaultSingleSelectionModel properties
|
selected
|
boolean
|
|
·
|
|
false
|
selectedIndex
|
int
|
·
|
|
·
|
-1
|
14.2.2.2 Events and methods
The
DefaultSingleSelectionModel object provides all the events and methods specified by the SingleSelectionModel interface discussed earlier.
|
No comments:
Post a Comment