Java Reference
In-Depth Information
// We will add the types menu items here using actions...
elementMenu.addSeparator();
JMenu colorMenu = new JMenu("Color"); // Color sub-menu
elementMenu.add(colorMenu); // Add the sub-menu
// We will add the color menu items here using actions...
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element menu
}
// We will add inner classes defining action objects here...
// We will add action objects as members here...
private JMenuBar menuBar = new JMenuBar(); // Window menu bar
private Color elementColor = DEFAULT _ ELEMENT _ COLOR; // Current element color
private int elementType = DEFAULT _ ELEMENT _ TYPE; // Current element type
}
Note that we have put the statement to set the default close operation as EXIT _ ON _ CLOSE back in so we
won't need to call dispose() and exit() in the window event handler. The old inner classes have
been deleted, as well as the fields storing references to menu items. All the code to create the menu
items has been wiped as well, along with the code that added the listeners. We are ready to begin
reconstruction. We can rebuild it, stronger, faster, better!
Defining Action Classes
We will need three inner classes defining actions, one for the File menu items, another for the element type
menu items, and the third for element colors. We will derive all these from the AbstractAction class that
already implements the Action interface. The AbstractAction class has three constructors:
Method
Description
AbstractAction()
Defines an object with a default name and icon.
AbstractAction(String name)
Defines an object with the name specified by the
argument and a default icon.
AbstractAction(String name,
Icon icon)
Defines an object with the name and icon specified
by the arguments.
The AbstractAction class definition already provides the mechanism for storing action properties.
For the last two constructors, the argument values that are passed will be stored using the standard keys
that we described earlier. For the moment, we will only take advantage of the second constructor, and
leave icons till a little later.
We can define the FileAction inner class as follows:
Search WWH ::




Custom Search