JFC actions

Use the powerful Command pattern with the JFC Action interface to build a reusable GUI-command library

1 2 Page 2
Page 2 of 2

However, the CutAction action hardcodes a text label and icon name. It makes no sense to feed this action a paste command. If you did feed it a different command type, you would have the wrong label and icon. By subclassing the command interface and defining new command types, we can write convenience actions that will take only the proper type of command. While CommandAction provides everything that we need for pluggable actions, it is nice to have specialized actions that know their label and icon. This way we can build a new command and plug it into a smarter action that already knows the command's icon and label, which speeds up development since you don't have to create icons and then put it all together into an action. Once you defined these specialized actions, they can be used across GUIs. If we simply used CommandAction, we would have to recreate the cut action in each GUI.

So, to create specialized actions, we need to:

  1. Define the subcommand interface
  2. Create the specialized action class

Both steps are fairly simple. Step 1 entails extending the CommandIF interface or some other CommandIF sub-interface. Step 2 entails extending the CommandAction and providing a new constructor, along with a label and an optional icon.

Figure 4. File commands

By following this recipe, it is possible to create a reusable library of common GUI actions, including those options normally found in the File and Edit menus. Instead of reproducing all of that code here, I've created a reusable library of commands. Figures 3, 4, and 5 model the library's object structure.

The commands include:

  • File: New, Open, Save, Save As, Print, Close, and Exit
  • Edit: Cut, Copy, Paste, Delete, Select All, and Deselect All
Figure 5. Edit commands

Each command interface has a corresponding action class. (See Resources to download the action library.)

Conclusion

Object-oriented programming techniques bring numerous benefits to software design and development. The Command pattern simply extends object-oriented design principles to include request logic. By combining the Command pattern and the JFC Action, we can easily bring the benefits of decoupled application logic to the Java GUI. Once it is designed to take advantage of the Command pattern, it is easy to add sophisticated functionality to almost any Java GUI.

Tony Sintes is a senior consultant specializing in telecommunications consulting at ObjectWave Corporation. (http://www.objectwave.com/) Tony is also the JavaWorld Q&A expert. Outside all of this "computer techno mumbo jumbo," Tony enjoys spending time with his wife Amy and tending to his marine aquariums.

Learn more about this topic

  • Source code resources
  • GUI Resources
  • The Pattern Languages of Program Design series
  • More pattern resources

1 2 Page 2
Page 2 of 2