Java Reference
In-Depth Information
Handling JCheckBoxMenuItem Selection Events
With a
JCheckBoxMenuItem
, you can attach many different listeners for a great variety of events:
•
MenuDragMouseListener
and
MenuKeyListener
from
JMenuItem
•
ActionListener
,
ChangeListener
, and
ItemListener
from
AbstractButton
•
AncestorListener
and
VetoableChangeListener
from
JComponent
•
ContainerListener
and
PropertyChangeListener
from
Container
•
ComponentListener
,
FocusListener
,
HierarchyBoundsListener
,
HierarchyListener
,
InputMethodListener
,
KeyListener
,
MouseListener
,
MouseMotionListener
, and
MouseWheelListener
from
Component
Although you can listen for 18 different types of events, the most interesting are
ActionEvent
and
ItemEvent
, described next.
Listening to JCheckBoxMenuItem Events with an ActionListener
Attaching an
ActionListener
to a
JCheckBoxMenuItem
allows you to find out when the menu
item is selected. The listener is told of the selection, but not of the new state. To find out the
selected state, you must get the model for the event source and query the selection state, as the
following sample
ActionListener
source shows. This listener modifies both the check box text
and the icon label, based on the current selection state.
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
Icon girlIcon = new ImageIcon("girl-r.jpg");
Icon boyIcon = new ImageIcon("boy-r.jpg");
AbstractButton aButton = (AbstractButton)event.getSource();
boolean selected = aButton.getModel().isSelected();
String newLabel;
Icon newIcon;
if (selected) {
newLabel = "Girl";
newIcon = girlIcon;
} else {
newLabel = "Boy";
newIcon = boyIcon;
}
aButton.setText(newLabel);
aButton.setIcon(newIcon);
}
};
■
Note
Keep in mind that you can also associate an
Action
from the constructor that can do the
same thing.