home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book Home Java Enterprise in a Nutshell Search this book

3.3. Actions

A GUI application often allows a user to invoke an operation in a number of different ways. For example, the user may be able to save a file by either selecting an item from a menu or clicking on a button in a toolbar. The resulting operation is exactly the same; it is simply presented to the user through two different interfaces.

Swing defines a simple but powerful javax.swing.Action interface that encapsulates information about such an operation. The Action interface extends the ActionListener interface, so it contains the actionPerformed() method. It is this method that you implement to actually perform the desired action. Each Action object also has an arbitrary set of name/value pairs that provide additional information about the action. The values typically include: a short string of text that names the operation, an image that can be used to represent the action graphically, and a longer string of text suitable for use in a tooltip for the action. In addition, each Action object has an enabled property and a setEnabled() method that allows it to be enabled and disabled. (If there is no text selected in a text editor, for example, the "Cut" action is usually disabled.)

You can add an Action object directly to a JMenu or JToolBar component. When you do this, the component automatically creates a JMenuItem or JButton to represent the action, making the action's operation available to the user and displaying the action's textual description and graphical image as appropriate. When an action is disabled, the JMenuItem or JButton component that represents the action displays it in a grayed-out style and does not allow it to be selected or invoked.

One shortcoming of working with actions is that there is no way to tell a JMenuBar or JToolBar to display just text or just icons for actions. Although you might like an action's name to be displayed in a menu and its icon to be displayed in a toolbar, both JMenuBar and JToolBar display an action's textual name and its icon.

The Action interface helps you implement a clean separation between GUI code and application logic. Remember, however, that you cannot just instantiate Action objects directly. Since Action is a kind of ActionListener, you must define an individual subclass of Action that implements the actionPerformed() method for each of your desired actions. The AbstractAction class is helpful here; it implements everything except the actionPerformed() method.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.