Java Reference
In-Depth Information
Add this definition to the SketchFrame class following the previous inner class. The only extra code
here compared to the previous action class is that we retain the typeID concept to identify the element
type. This makes the listener operation simple and fast. Because each object corresponds to a particular
element type, there is no need for any testing of the event - we just store the current typeID as the new
element type in the SketchFrame class object. We won't be adding accelerator key combinations for
type menu items so we don't need to provide for them in the class.
Add the following statement to the SketchFrame class for the members that will store references to the
TypeAction objects:
// Element type actions
private TypeAction lineAction, rectangleAction, circleAction, curveAction;
The third inner class is just as simple:
// Handles color menu items
class ColorAction extends AbstractAction {
public ColorAction(String name, Color color) {
super(name);
this.color = color;
}
public void actionPerformed(ActionEvent e) {
elementColor = color;
// This is temporary - just to show it works
getContentPane().setBackground(color);
}
private Color color;
}
We also use the same idea that we used in the listener class for the color menu items in the previous
implementation of SketchFrame . Here we have a statement in the actionPerformed() method that
sets the background color of the content pane to the element color. When you click on a color menu
item, the background color of the content pane will change so you will be able to see that it works. We'll
remove this code later.
Add the following statement to the SketchFrame class for the color action members:
// Element color actions
private ColorAction redAction, yellowAction,
greenAction, blueAction;
We can try these action classes out now.
Try It Out - Actions in Action
All we need to do to create the menu items is use the add() method to add a suitable Action object to
a menu. This all happens in the SketchFrame constructor - with the aid of a helper method that will
economize on the number of lines of code:
Search WWH ::




Custom Search