Action Map Action
Posted by Rob Camick on December 6, 2008
The ActionMap contains predefined Actions for a given Swing component. Many, but not all, of these Actions are mapped to a KeyStroke so they can be invoked by the user. Regardless of whether an Action is mapped to a KeyStroke or not, there may be times when you want to use a button or a menu item to invoke one of these existing actions. These components support the setAction() method, so all we need to do is retrieve the Action from the ActionMap.
Well, actually its not quite that easy. Sure we can easily retrieve the Action and add it to a button, but the problem is that the source of the ActionEvent will now be the button, not the component we want to perform the Action on. This may, or may not, be a problem depending on the Action.
The ActionMapAction class will act as a simple wrapper class. You specify the action name identifier used in the ActionMap and it will find the related Action. Whenever it is invoked it will create an new ActionEvent using the specifed Component as the source Component and then invoke the Action from the ActionMap.
For example, creating a button that invokes an Action on a text field is as simple as:
JTextField textField = new JTextField();
Action nextWord = new ActionMapAction(
"Select Next Word", textField, "selection-next-word");
JButton nextButton = new JButton(nextWord);
Clicking on the button would result in…
Check out the Key Bindings entry below for a list of all the currently defined Actions for each component. Now you can easily invoke existing Actions with the keyboard or the mouse.