Java Reference
In-Depth Information
private int type;
// Store the type for the
menu
}
Directory "Sketcher 4 with element type listeners"
Now you can use objects of this class as listeners for the menu items. Add the following code to the
SketcherFrame constructor, after the code that sets up the type menu items for the Elements menu just
before the last two lines of the constructor:
// Add type menu item listeners
lineItem.addActionListener(new TypeListener(LINE));
rectangleItem.addActionListener(new TypeListener(RECTANGLE));
circleItem.addActionListener(new TypeListener(CIRCLE));
curveItem.addActionListener(new TypeListener(CURVE));
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element
menu
}
Directory "Sketcher 4 with element type listeners"
It is also necessary to add an import statement to the source file for the SketcherFrame class for Ac-
tionListener and ActionEvent :
import java.awt.event.*;
Recompile Sketcher and see how it looks.
How It Works
The application window won't look any different, as the listeners just set the current element type in
the SketcherFrame object. The listener class is remarkably simple. Each listener object stores the type
corresponding to the menu item that is passed as the constructor argument. When an event occurs, the
actionPerformed() method just stores the type in the listener object in the elementType member of
the SketcherFrame object.
Now you can do the same for the color menu items.
TRY IT OUT: Implementing Color Menu Item Listeners
You define another inner class to SketcherFrame that defines listeners for the Color menu items:
Search WWH ::




Custom Search