Java Reference
In-Depth Information
When we construct the element objects, we use the
elementType
and
elementColor
members to set
the state of each menu item. Only the element type menu item corresponding to the default type set in
elementType
will be checked because that's the only comparison that will produce a true result as an
argument to the
JRadioButtonMenuItem
constructor. The mechanism is the same for the color menu
items, but note that we use the
equals()
method defined in the
Color
class for a valid comparison.
We might just get away with using
==
since we are only using constant
Color
values defined in the
class, but as soon as we use a color that is not one of these, this would no longer work. Of course, we
have to use
==
for the element type items because the IDs are of type
int
.
Having got that sorted out, we can have a go at implementing the listeners for the
Elements
menu,
starting with the type menu items.
Try It Out - Handling Events for the Element Type Menu
We will add an inner class that will define listeners for the menu items specifying the element type. This
class will implement the
ActionListener
interface because we want to respond to actions on these
menu items. Add the following definition as an
inner
class to
SketchFrame
:
// Handles element type menu items
class TypeListener implements ActionListener {
// Constructor
TypeListener(int type) {
this.type = type;
}
// Sets the element type
public void actionPerformed(ActionEvent e) {
elementType = type;
}
private int type; // Store the type for the menu
}
Now we can use objects of this class as listeners for the menu items. Add the following code to the
SketchFrame
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
}
It will also be necessary to add the following two
import
statements to the
SketchFrame
class.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
Recompile Sketcher and see how it looks.