Java Reference
In-Depth Information
11.4.6
Centralized receipt of events
In order to make our
ImageViewer
object be the single listener to all events from the menu, we
have to do three things:
1
We must declare in the class header that it implements the
ActionListener
interface.
2
We have to implement a method with the signature
public void actionPerformed(ActionEvent e)
This is the only method declared in the
ActionListener
interface.
3
We must call the
addActionListener
method of the menu item to register the
ImageViewer
object as a listener.
Numbers 1 and 2—implementing the interface and defining its method—ensure that our object
is a subtype of
ActionListener
. Number 3 then registers our own object as a listener for the
menu items. Code 11.3 shows the source code for this in context.
Code 11.3
Adding an action
listener to a menu item
public
class
ImageViewer
implements
ActionListener
{
//
Fields and constructor omitted.
public
void
actionPerformed(ActionEvent event)
{
System.out.println(
"Menu item: "
+ event.getActionCommand());
}
/**
* Create the Swing frame and its content.
*/
private
void
makeFrame()
{
frame =
new
JFrame(
"ImageViewer"
);
makeMenuBar(frame);
//
Other GUI building code omitted.
}
/**
* Create the main frame's menu bar.
* @param frame The frame the menu bar should be added to.
*/
private
void
makeMenuBar(JFrame frame)
{
JMenuBar menubar =
new
JMenuBar();
frame.setJMenuBar(menubar);
Search WWH ::
Custom Search