Java Reference
In-Depth Information
Listening to JMenuItem Events with an ActionListener
The better listener to attach to a
JMenuItem
is the
ActionListener
, or passing an
Action
to the
constructor. It allows you to find out when a menu item is selected. Any registered
ActionListener
objects would be notified when a user releases the mouse button over a
JMenuItem
that is part
of an open menu. Registered listeners are also notified if the user employs the keyboard
(whether with arrow keys or mnemonics) or presses the menu item's keyboard accelerator to
make a selection.
You must add an
ActionListener
to every
JMenuItem
for which you want an action to happen
when selected. There's no automatic shortcut allowing you to register an
ActionListener
with
a
JMenu
or
JMenuBar
and have all their contained
JMenuItem
objects notify a single
ActionListener
.
The sample program shown in Listing 6-1 associates the same
ActionListener
with every
JMenuItem
:
class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Selected: " + e.getActionCommand());
}
}
However, more frequently, you would associate a different action with each item, so that
each menu item can respond differently.
■
Tip
Instead of creating a custom
ActionListener
for the component, and adding it as a listener, you
can also create a custom
Action
and call
setAction()
on the component.
Listening to JMenuItem Events with a MenuKeyListener
The
MenuKeyEvent
is a special kind of
KeyEvent
used internally by the user interface classes for
a
JMenu
and
JMenuItem
, allowing the components to listen for when their keyboard mnemonic
is pressed. To listen for this keyboard input, each menu component registers a
MenuKeyListener
to pay attention to the appropriate input. If the keyboard mnemonic is pressed, the event is
consumed and not passed to any registered listeners. If the keyboard mnemonic is not pressed,
any registered key listeners (instead of menu key listeners) are notified.
The
MenuKeyListener
interface definition follows:
public interface MenuKeyListener extends EventListener {
public void menuKeyPressed(MenuKeyEvent e);
public void menuKeyReleased(MenuKeyEvent e);
public void menuKeyTyped(MenuKeyEvent e);
}
Normally, you wouldn't register objects as this type of listener yourself, although you could
if you wanted to. If you do, and if a
MenuKeyEvent
happens (that is, a key is pressed/released),
every
JMenu
on the
JMenuBar
will be notified, as will every
JMenuItem
(or subclass) on an open
menu with a registered
MenuKeyListener
. That includes disabled menu items so that they can
consume a pressed mnemonic. The definition of the
MenuKeyEvent
class follows: