18.7. Using Actions

One difficulty with the code that you have added to support the menus is that it is very menu specific. What I mean by this is that if you are going to do a proper job on the Sketcher application, you will undoubtedly want it to have a toolbar. The toolbar will surely have a whole bunch of buttons that perform exactly the same actions as the menu items you have just implemented, so you'll be in the business of doing the same thing all over again in the toolbar context. Of course, the only reason I brought it up, as I'm sure you've anticipated, is that there is another way of working with menus, and that is to use an Action object.

An Action object is a bit of a strange beast. It can be quite hard to understand at first, so I'll take it slowly. First of all let's look at what is meant by an "action" here, as it is a precise term in this context. An action is an object of any class that implements the javax.swing.Action interface. This interface declares methods that operate on an action object—for example, storing properties relating to the action, enabling it and disabling it. The Action interface happens to extend the ActionListener interface, so an action object is a listener as well as an action. Now that you know an Action object can get and set properties and is also a listener, how does that help us in implementing the Sketcher GUI?

The answer is in the last capability of an Action object. Some Swing components, such as those of type JMenu and JToolBar ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.