mechanicalSPIRIT

B.T. Franklin's blog

« Back to blog

Java Programming Tip: Using Actions in Swing

One poorly-understood area of Swing seems to be the Action class. I don't know how many times I've seen big blocks of code stuffed to the brim setting various attributes of JButtons or JMenuItems and attaching listeners left and right. Wow! What if I told you all that stuff could be done in a single line, like this:

JButton activatorButton = new JButton( new ActivationAction() );

It's true! JButton has (and most of the other interactive Swing components have) a constructor that takes nothing but a single Action. From this Action, Swing is able to configure nearly everything else of importance about the component.

Actions are interesting little classes. In general, you create one by extending AbstractAction to represent a single specific user action, not in terms of the component being triggered, but rather in terms of the user's desired result, such as "Save File". In the Action's constructor, you build up a set of attributes stored by the Action, which are then retrieved by the component (such as the JButton) when the Action is attached. Moreover, the Action serves as a listener to the component, so when the JButton is pressed, the Action is the class that hears the call.

This design enables your application to be written in terms of a set of actions rather than a set of buttons. It's much easier to add and remove entire blocks of functionality (since multiple components can utilize the same Action class) and it removes a lot of the complexity introduced by having "a listener for everything".

In my opinion, this is one of the most elegant aspects of the Swing framework, and sadly, also one of the most underutilized.