Java Reference
In-Depth Information
// 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;
}
Directory "Sketcher 5 with element color listeners"
You just need to create listener objects and add them to the color menu items. Add the following code at
the end of the SketcherFrame constructor after the code that sets up the Color submenu:
// Add color menu item listeners
redItem.addActionListener(new ColorListener(RED));
yellowItem.addActionListener(new ColorListener(YELLOW));
greenItem.addActionListener(new ColorListener(GREEN));
blueItem.addActionListener(new ColorListener(BLUE));
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element
menu
}
Directory "Sketcher 5 with element color listeners"
This adds a listener object for each menu item in the Color menu. The listeners don't do anything yet,
but they will, eventually. You could add an output statement to the actionPerformed() method if you
wanted confirmation of when it is executed:
System.out.println("Color event " + e.toString());
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
Search WWH ::




Custom Search