Java Reference
In-Depth Information
Code 11.3
Adding an action
listener to a menu item
// create the File menu
JMenu fileMenu = new JMenu( "File" );
JMenuItem openItem = new JMenuItem( "Open" );
openItem.addActionListener( this );
JMenuItem quitItem = new JMenuItem( "Quit" );
quitItem.addActionListener( this );
Note especially the lines
JMenuItem openItem = new JMenuItem("Open");
in the code example. Here, a menu item is created, and the current object (the ImageViewer
object itself) is registered as an action listener by passing this as a parameter to the addAc-
tionListener method.
The effect of registering our object as a listener with the menu item is that our own action-
Performed method will be called by the menu item each time the item is activated. When our
method is called, the menu item will pass along a parameter of type ActionEvent that provides
some details about the event that has occurred. These details include the exact time of the event,
the state of the modifier keys (the shift, control, and meta keys), a “command string,” and more.
The command string is a string that somehow identifies the component that caused the event.
For menu items, this is by default the label text of the item.
In our example in Code 11.3, we register the same action object for both menu items. This means
that both menu items will invoke the same actionPerformed method when they are activated.
In the actionPerformed method, we simply print out the command string of the item to demon-
strate that this scheme works. Here, we could now add code to properly handle the menu invocation.
This code example, as discussed this far, is available in the topic projects as project
imageviewer0-2 .
Exercise 11.7 Implement the menu-handling code, discussed above, in your own image-
viewer project. Alternatively, open the imageviewer0-2 project and carefully examine the source
code. Describe in writing and in detail the sequence of events that results from activating the
Quit menu item.
Exercise 11.8 Add another menu item called Save .
Search WWH ::

Custom Search