Recent articles:
Popular archives:
Java: A platform for platforms
Sun's reorg may seem promising to shareholders but it's also a scramble for position. The question now is whether Sun can,
or wants to, maintain its hold on Java technology. Especially with enterprise leaders like SpringSource and RedHat investing
heavily in Java's future as a platform for platforms
Also see:
Discuss: Java: A platform for platforms?
In this article, we will explore the Command pattern and JFC Actions. Using the JFC Action and Java interfaces, we will develop a library of commands that can be found in most applications. These commands include the File commands: New, Open, Save, Save As, Print, Close, and Exit; as well as the Edit commands: Cut, Copy, Paste, Delete, Select All, and Deselect all.
ActionListener callback. Let's look at the javax.swing.Action interface:public interface Action extends ActionListener
{
public static final String DEFAULT = "Default";
public static final String NAME = "Name";
public static final String SHORT_DESCRIPTION = "ShortDescription";
public static final String LONG_DESCRIPTION = "LongDescription";
public static final String SMALL_ICON = "SmallIcon";
public void addPropertyChangeListener(PropertyChangeListener listener);
public Object getValue(String key);
public boolean isEnabled();
public void putValue(String key, Object value);
public void removePropertyChangeListener(PropertyChangeListener listener);
public void setEnabled(boolean b);
}
The class javax.swing.AbstractAction provides a basic action implementation. To create an action, we simply extend AbstractAction, provide the display information, and implement the action logic by defining the actionPerformed() method. Unless there is a compelling reason for you to reimplement the Action interface yourself, AbstractAction should suffice as an inheritable in most cases.
On the surface, actions may not seem very useful. However, they provide many benefits, which are listed below:
actionPerformed() method contains all of the switch logic for each button and menu item in the window. In contrast, with actions we can avoid
this switch nonsense by assigning an Action instance to each GUI construct. This is an approach that offers an elegant object-oriented alternative to the switch/case
mess that generally exists in Java GUI code.
Unfortunately, actions do not come without a price: the logic of the command is often mired inside the action itself. Actions
tempt us to place all of the logic inside of the actionPerformed() method. Unfortunately, whenever something changes, you'll need to rewrite your actions. As a result, you can't easily take
an action to another GUI. Instead, you are forced to constantly rewrite or extend the action portion of your code, even if
these actions present the same command.