Java Reference
In-Depth Information
■
Note
SingleSelectionModel
also serves as the selection model for
JTabbedPane
, a class described
in Chapter 11.
The interface definition for
SingleSelectionModel
follows:
public interface SingleSelectionModel {
// Listeners
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
// Properties
public int getSelectedIndex();
public void setSelectedIndex(int index);
public boolean isSelected();
// Other Methods
public void clearSelection();
}
As you can see, in addition to the selection index, the interface requires maintenance of a
ChangeListener
list to be notified when the selection index changes.
The default Swing-provided implementation of
SingleSelectionModel
is the
DefaultSingleSelectionModel
class. For both
JMenuBar
and
JPopupMenu
, it's very unlikely that
you will change their selection model from this default implementation.
The
DefaultSingleSelectionModel
implementation manages the list of
ChangeListener
objects. In addition, the model uses a value of -1 to signify that nothing is currently selected.
When the selected index is -1,
isSelected()
returns
false
; otherwise, the method returns
true
.
When the selected index changes, any registered
ChangeListener
objects will be notified.
JMenuItem Class
The
JMenuItem
component is the predefined component that a user selects on a menu bar. As a
subclass of
AbstractButton
,
JMenuItem
acts as a specialized button component that behaves
similarly to a
JButton
. Besides being a subclass of
AbstractButton
, the
JMenuItem
class shares
the data model of
JButton
(
ButtonModel
interface and
DefaultButtonModel
implementation).
Creating JMenuItem Components
Six constructors for
JMenuItem
follow. They allow you to initialize the menu item's string or icon
label and the mnemonic of the menu item. There's no explicit constructor permitting you to
set all three options at creation time, unless you make them part of an
Action
.