Action Interface Core Java

It is common to have multiple ways to activate the same command. The user can choose a certain function through a menu, a keystroke, or a button on a toolbar. This is easy to achieve in the AWT event model: link all events to the same listener. For example, suppose

blueAction is an action listener whose actionPerformed method changes the background color to blue. You can attach the same object as a listener to several event sources:

  • A toolbar button labeled “Blue”
  • A menu item labeled “Blue”
  • A keystroke CTRL+B

Then the color change command is handled in a uniform way, no matter whether it was caused by a button click, a menu selection, or a key press.

The Swing package provides a very useful mechanism to encapsulate commands and to attach them to multiple event sources: the Action interface. An action is an object that encapsulates

  • A description of the command (as a text string and an optional icon); and
  • Parameters that are necessary to carry out the command (such as the requested color in our example).

The Action interface has the following methods:

The first method is the familiar method in the ActionListener interface: in fact, the Action interface extends the ActionListener interface. Therefore, you can use an Action object whenever an ActionListener object is expected.

The next two methods let you enable or disable the action and check whether the action is currently enabled. When an action is attached to a menu or toolbar and the action is disabled, then the option is grayed out.

The putValue and getValue methods let you store and retrieve arbitrary name /value pairs in the action object. A couple of important predefined strings, namely, Action. NAME and Action. SMALL_ICON, store action names and icons into an action object:

all predefined action table names.

Predefined Action Table Names

Predefined Action Table Names

If the action object is added to a menu or toolbar, then the name and icon are automatically retrieved and displayed in the menu item or toolbar button. The SHORT _DESCRIPTION value turns into a tooltip.

The final two methods of the Action interface allow other objects, in particular menus or toolbars that trigger the action, to be notified when the properties of the action object change. For example, if a menu is added as a property change listener of an action object and the action object is subsequently disabled, then the menu is called and can gray out the action name. Property change listeners are a general constructthat is a part of the “JavaBeans” component model.

Note that Action is an interface, not a class. Any class implementing this interface must implement the seven methods we just discussed. Fortunately, a friendly soul has provided a class AbstractAction that implements all methods except for action Performed. That class takes care of storing all name /value pairs and managing the property change listeners. You simply extend AbstractAction and supply an action Performed method.

Let’s build an action object that can execute color change commands. We store the name of the command, an icon, and the desired color. We store the color in the table of name/ value pairs that the AbstractAction class provides. Here is the code for the ColorAction class.

The constructor sets the name/value pairs, and the action Performed method carries out the color change action.

Our test program creates three objects of this class, such as Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);

Next, let’s associate this action with a button. That is easy because we can use a JButton constructor that takes an Action object.

That constructor reads the name and icon from the action, sets the short description as the tooltip, and sets the action as the listener. You can see the icons and a tooltip.

Buttons display the icons from the action objects

Buttons display the icons from the action objects

As we demonstrate in the next section, it is just as easy to add the same action to a menu.

Finally, we want to add the action objects to keystrokes so that the actions are carried out when the user types keyboard commands. To associate actions with key strokes, you first need to generate objects of the Key Stroke class. This is a convenience class that encapsulates the description of a key. To generate a Key Stroke object, you don’t call a constructor but instead use the static getKeyStroke method of the KeyStroke class.

To understand the next step, you nee to know the concept of keyboard focus. A user interface can have many buttons, menus, scrollbars, and other components. When you hit a key, it is sent to the component that has focus. That component is usually (but not always) visually distinguished. For example, in the Java Look and Feel, a button with focus has a thin rectangular border around the button text. You can use the TAB key to move the focus between components. When you press the SPACE key, the button withfocus is clicked. Other keys carry out different actions; for example, the arrow keys can move a scrollbar.

However, in our case, we do not want to send the keystroke to the component that has focus. Otherwise, each of the buttons would need to know how to handle the CTRL+Y, CTRL+B, and CTRL+R keys.

This is a common problem, and the Swing designers came up with a convenient solution for solving it. Every JComponent has three input maps, each mapping KeyStroke objects to associated actions. The three input maps correspond to three different conditions.

Input Map Conditions

Input Map Conditions

Keystroke processing checks these maps in the following order:

  1. Check the WHEN_FOCUSED map of the component with input focus. If the keystroke exists, execute the corresponding action. If the action is enabled, stop processing.
  2. Starting from the component with input focus, check the WHEN _ANCESTOR _OF _FOCUSED_ COMPONENT maps of its parent components. As soon as a map with the keystroke isfound, execute the corresponding action. If the action is enabled, stop processing.
  3. Look at all visible and enabled components in the window with input focus that have this keystroke registered in a WHEN _IN _FOCUSED _WINDOW map. Give these components (in the order of their keystroke registration) a chance to execute the corresponding action. As soon as the first enabled action is executed, stop processing.

This part of the process is somewhat fragile if a keystroke appears in more than one WHEN _IN _FOCUSED _WINDOW map.

You obtain an input map from the component with the getInputMap method. Here is an example:

The WHEN _FOCUSED condition means that this map is consulted when the current component has the keyboard focus. In our situation, that isn’t the map we want. One of the buttons, not the panel, has the input focus. Either of the other two map choices works fine for inserting the color change keystrokes. We use WHEN _ANCESTOR _OF _FOCUSED _COMPONENT in our example program.

The InputMap doesn’t directly map KeyStroke objects to Action objects. Instead, it maps to arbitrary objects, and a second map, implemented by the ActionMap class, maps objects to actions. That makes it easier to share the same actions among keystrokes that come from different input maps.

Thus, each component has three input maps and one action map. To tie them together, you need to come up with names for the actions. Here is how you can tie a key to an action:

It is customary to use the string "none" for a do-nothing action. That makes it easy to deactivate a key:

CAUTION: The JDK documentation suggests using the action name as the action’s key. We don’t think that is a good idea. The action name is displayed on buttons and menu items; thus, it can change at the whim of the UI designer and it may be translated into multiple languages. Such unstable strings are poor choices for lookup keys. Instead, we recommend that you come up with action names that are independent of the displayed names.

To summarize, here is what you do to carry out the same action in response to a button,

a menu item, or a keystroke:
  1. Implement a class that extends the AbstractAction class. You may be able to use the same class for multiple related actions.
  2. Construct an object of the action class.
  3. Construct a button or menu item from the action object. The constructor will read the label text and icon from the action object.
  4. For actions that can be triggered by keystrokes, you have to carry out additional steps. First locate the top-level component of the window, such as a panel that contains all other components.
  5. Then get the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map of the top-level component. Make a KeyStroke object for the desired keystroke. Make an action key object, such as a string that describes your action. Add the pair (keystroke, action key) into the input map.
  6. Finally, get the action map of the top-level component. Add the pair (action key,action object) into the map.

javax.swing.Action

  • boolean isEnabled()
  • void setEnabled(boolean b)
    gets or sets the enabled property of this action.
  • void putValue(String key, Object value)
    places a name/value pair inside the action object.
  • Object getValue(String key)
    returns the value of a stored name/value pair.

javax.swing.KeyStroke

  • static Key Stroke get Key Stroke (String description) constructs a keystroke from a humanly readable description (a sequence of white space -delimited strings). The description starts with zero or more modifiersshift control ctrl meta alt altGraph and ends with either the string typed, followed by

a one-character string (for example, "typed a"), or an optional event specifier ( pressed—the default—or released), followed by a key code. The key code, when prefixed with VK_, should correspond to a KeyEvent constant; for example, "INSERT"corresponds to KeyEvent .VK_INSERT.

  • ActionMap getActionMap()
    returns the map that associates action map keys (which can be arbitrary objects) with Action objects.
  • InputMap getInputMap(int flag)>

gets the input map that maps key strokes to action map keys



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics