Java: Action, AbstractAction

The javax.swing.Action interface, and the corresponding class, javax.swing.AbstractAction, provide a useful mechanism to implement action listeners that can be shared and coordinated.

Subclassing. You must subclass AbstractAction (the hint is the word "abstract" in the class name). The minimum you need to do is override actionPerformed to specify what you want the Action to do. See examples below.

AbstractAction constructors, methods, and fields

Constructors
act = new AbstractAction(String name); Specifies name for buttons, etc.
act = new AbstractAction(String name, Icon smallIcon); Specifies name and an icon (eg, that will appear on a toolbar buttons).
Some Methods
b = act.isEnabled() Returns true if this Action is enabled.
 act.setEnabled(boolean enabled) Sets the status of this Action.
 act.putValue(String key, Object value) Sets the value of property key to value.
obj = act.getValue(String key) Gets the value of property key.
Some Property Fields (use putValue() to explicitly set these fields)
 ACCELERATOR_KEYAccelerator key.
 MNEMONIC_KEY Mnemonic key.
 NAME Name for buttons and menu items.
 SHORT_DESCRIPTIONUsed as tooltip text.
 SMALL_ICON Used for toolbars.

Usage

Actions can be used directly in the add() method of some containers (eg, menus and toolbars), or in constructors for buttons and menu items.

fileMenu.add(exitAction);  // Add directly to menu.  Uses Action's text, icon.

If you don't want all the functionality of an Action, create the desired component from the Action, then modify it.

JMenuItem exitItem = new JMenuItem(exitAction);  // Use to create component.
exitItem.setIcon(null);                          // Modify to suppress the icon.
fileMenu.add(exitItem);

Example - Simple anonymous class

  1 
  2 
  3 
  4 
  5 
  6 
  7 
Action openAction = new AbstractAction("Open...") {
    public void actionPerformed(ActionEvent e) {
        openFile();  // Do what you want here.
    }
};
. . .
fileMenu.add(openAction);  // Add action to menu

The Simple Editor example shows the use of anonymous subclassing.

Example - Defining subclass to get additional functionality

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
Action openAction = new OpenAction("Open...", folderIcon, "Open file.", KeyEvent.VK_O);
. . .
fileMenu.add(openAction);  // Add action to menu
. . .
class OpenAction extends AbstractAction {
    //-- Define a constructor which takes parameters you want to set.
    public OpenAction(String text, ImageIcon icon, String tooltip, int mnemonic) {
        super(text, icon); //  AbstractAction constructor takes only two params.
        putValue(SHORT_DESCRIPTION, tooltip);  // Will appear as tooltip text.
        putValue(MNEMONIC_KEY, new Integer(mnemonic));
    }
    
    //-- Override actionPerformed to do what you want.
    public void actionPerformed(ActionEvent e) {
        openFile();  // Do what you want here.
    }
}