Java Reference
In-Depth Information
We have added four blocks of code. The first two are for the file menu, one creating the action object
and the other calling a helper method,
addMenuItem()
, to create the menu items. The other two are
for the element type and color menus. We create the action items for these menus in the arguments to
the helper method calls. It's convenient to do this, as the constructor calls are relatively simple.
The helper method will add an item specified by its second argument to the menu specified by the first.
By declaring the second argument as type
Action
, we can pass a reference to an object of any class
type that implements the
Action
interface, so this includes any of our action classes. Here's the code:
private JMenuItem addMenuItem(JMenu menu, Action action) {
JMenuItem item = menu.add(action); // Add the menu item
KeyStroke keystroke = (KeyStroke)action.getValue(action.ACCELERATOR
_
KEY);
if(keystroke != null)
item.setAccelerator(keystroke);
return item; // Return the menu item
}
As you can see, the method takes care of adding the accelerator key for the menu item if one has been
defined for the
Action
object. If there isn't one, the
getValue()
method will return
null
, so it's easy
to check. We don't need access to the menu item that is created in the method at the moment since it is
added to the menu. However, it is no problem to return the reference from the method and it could be
useful if we wanted to add code to do something with the menu item at some point.
If you compile and run Sketcher, you will get a window that looks like this:
How It Works
We create an
Action
object for each item in the file menu. We then call our private
addMenuItem()
method for each item in turn to create the menu items corresponding to the
Action
objects, and add
them to the file menu. The
addMenuItem()
method automatically adds an accelerator key for a menu
item if it exists in the
Action
object. We declare the
addMenuItem()
method as
private
because it
has no role outside of the
SketchFrame
class and therefore should not be accessible.