Java Reference
In-Depth Information
putValue(NAME, "Save All");
This stores the string
"Save All"
as the object corresponding to the standard key
NAME
. A
menu item created from the action object displays
"Save All"
as the menu item text.
•
Object getValue(String key)
: This retrieves the object from the map corresponding to the key
key
. To retrieve a small icon from an action object,
action
, you can write:
ImageIcon lineIcon = (ImageIcon)(action.getValue(SMALL_ICON));
•
boolean isEnabled()
: This returns
true
if the action object is enabled and
false
otherwise.
•
void setEnabled(boolean state)
: This sets the
Action
object as enabled if
state
is
true
and
disabled if it is
false
. This operates on both the toolbar button and the menu item if they have
been created using the same
Action
object.
•
void addPropertyChangeListener(PropertyChangeListener listener)
: This adds the
listener passed as an argument, which listens for changes to properties such as the enabled state of
the object. This is used by a container for an
Action
object to track property changes.
•
void removePropertyChangeListener(PropertyChangeListener listener)
: This removes
the listener passed as an argument. This is also for use by a
Container
object.
Of course, because the
Action
interface extends the
ActionListener
interface, it also incorporates the
Ac-
tionPerformed()
method that you are already familiar with. So far, all you seem to have gained with this
interface is a license to do a lot of work in implementing it, but it's not as bad as that. The
javax.swing
package defines the
AbstractAction
class that already implements the
Action
interface. If you extend this
class to create your own action class, you get a basic infrastructure for free, including the ability to handle
events. Let's try it out in the context of Sketcher.
Using Actions as Menu Items
Using
Action
objects involves major surgery on the
SketcherFrame
class. Although you throw away all
those fancy varieties of menu items you spent so much time putting together, at least you know how they
work now, and you end up with much less code after re-engineering the class, as you later see. As the saying
goes, you've got to crack a few eggs to make a soufflé.
You go back nearly to square one and reconstruct the class definition. First you delete a lot of code from
the existing class definition. Comments show where you add code to re-implement the menus using actions.
Get your definition of the
SketcherFrame
class to the following state:
// Frame for the Sketcher application
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import static java.awt.event.InputEvent.*;
import static java.awt.AWTEvent.*;
import static java.awt.Color.*;
import static Constants.SketcherConstants.*;