Posted by Rob Camick on November 3, 2008
Swing components use Actions to provide basic functionality for the component. Of course these Actions can never provide all the functionality you desire and there may be times when you need to customize the default behaviour of an Action.
One obvious way to do this is to dig into the source code, copy it and customize it. But this is not always practical as more often than not, the Action will use protected or private methods or variables.
Another option is to create a custom Action that has the ability to invoke the components default Action. Before we can use this approach we need to be able to access the original Action. This can be done in one of two ways:
- via the ActionMap – the “action key” is used to access the ActionMap to retrieve the Action.
- via the InputMap – a KeyStroke is used to access the InputMap to find the “action key” for the KeyStroke. Once the “action key” is found the ActionMap can be accessed.
Note: check out the Key Binding link below for a complete list of the action keys and KeyStrokes used for each Swing component. Also, if you need more information about ActionMaps and InputMaps, it would be a good time to check out the “How to Use Key Bindings” tutorial link provide below.
Now that we have the original Action we need to ability to wrap the Action with our custom Action and add the custom Action to the ActionMap. It sounds like a lot of work to access and use the default Action. Well, thats why I created the WrappedAction class. Its goal was to make this process easier. This is accomplished by:
- accessing the original Action – this can be done by using a KeyStroke or the “action key”.
- retaining the original Action – this allows your custom Action to directly invoke the default Action. This is done by using the invokeOriginalAction(…) method in your custom Action.
- updating the ActionMap – your custom Action is now the default Action of the component
In general, the WrappedAction class is a convenience class that implements the above functionality so you don’t need to duplicate it every time you need a custom Action. However, the WrappedAction class is abstract so you will need to extend this class and implement the actionPerformed() method in your custom Action.
Still not sure why this class is helpfull? Well then stay tuned for my next entry which will give a practical example.