Java Reference
In-Depth Information
Example 10•16: Scribble.java (continued)
// These two methods specify the size of the icon
public int getIconHeight() { return 16; }
public int getIconWidth() { return 16; }
// This method draws the icon
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillRect(x, y, 16, 16);
}
}
/**
* This inner class defines an Action that uses JColorChooser to allow
* the user to select a drawing color
**/
class SelectColorAction extends AbstractAction {
public SelectColorAction() { super("Select Color..."); }
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(Scribble.this,
"Select Drawing Color",
scribblePane.getColor());
if (color != null) scribblePane.setColor(color);
}
}
}
Actions and Reflection
Example 10-16 demonstrated the use of
Action
objects, which allow an applica-
tion's command set to be easily presented to the user in menubars, toolbars, and
so on. The awkward part about working with
Action
objects, however, is that
each one must usually be defined as a class of its own. If you are willing to use
the Java Reflection API, however, there is an easier alternative. In Example 8-2 in
Chapter 8,
Reßection
, we saw the
Command
class—a class that encapsulates a
java.lang.reflect.Method
object, an array of arguments for the method, and the
object upon which the method is to be invoked. Calling the
invoke()
method of a
Command
object invokes the method. The most powerful feature of the
Command
class, however, is its static
parse()
method, which can create a
Command
by parsing
a textual representation of the method name and argument list.
The
Command
class implements the
ActionListener
interface, so
Command
objects
can be used as simple action listeners. But a
Command
is not an
Action
. Example
10-17 addresses this; it is a listing of
CommandAction.java
, a subclass of
AbstractAction
that uses a
Command
object to perform the action. Since the
Com-
mand
class does the hard work, the code for
CommandAction
is relatively simple.
Example 10•17: CommandAction.java
package com.davidflanagan.examples.gui;
import com.davidflanagan.examples.reflect.*;
import javax.swing.*;
import java.awt.event.*;
public class CommandAction extends AbstractAction {
Command command; // The command to execute in response to an ActionEvent