Java Reference
In-Depth Information
How It Works
It won't look any different as the listeners just set the current element type in the
SketchFrame
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
SketchFrame
object.
Now we can do the same for the color menu items.
Try It Out - Implementing Color Menu Item Listeners
We will define another class that is an inner class to
SketchFrame
that defines listeners for the
Color
menu items:
// Handles color menu items
class ColorListener implements ActionListener {
public ColorListener(Color color) {
this.color = color;
}
public void actionPerformed(ActionEvent e) {
elementColor = color;
}
private Color color;
}
We just need to create listener objects and add them to the menu items. Add the following code at the
end of the
SketchFrame
constructor after the code that sets up the
Color
submenu:
// Add color menu item listeners
redItem.addActionListener(new ColorListener(Color.RED));
yellowItem.addActionListener(new ColorListener(Color.YELLOW));
greenItem.addActionListener(new ColorListener(Color.GREEN));
blueItem.addActionListener(new ColorListener(Color.BLUE));
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element menu
}
This adds a listener object for each menu item in the
Color
menu.
How It Works
The
ColorListener
class works in the same way as the
TypeListener
class. Each class object
stores an identifier for the menu item for which it is listening - in this case a
Color
object
corresponding to the color the menu item sets up. The
actionPerformed()
method just stores the
Color
object from the listener object in the
elementColor
member of the
SketchFrame
object.
Of course, the menu doesn't quite work as it should. The menu item check marks are not being set
correctly, as you can see below. We want an exclusive check, as with the radio buttons; more than one
color at a time doesn't make sense: