Thursday, February 11, 2010 1:52 PM | rahel luethy | 1 comment(s)

Swing Actions: Representing selection state

The concept of actions as a separation of the controller logic from the visual representation is a very useful one. In Swing, a lot of views use an action as a template for construction: components like JButton or JMenuItem initialize their name, tooltip, or enabling state based on a set of action properties. Such properties (values assigned to pre-defined keys) can be configured on an action instance via

myAction.putValue(Action.SHORT_DESCRIPTION, "Whatever");

and changes to a property value automatically update the state of all views that depend on it.

Up to Java 1.6, one of the biggest drawbacks was that actions didn't cover toggles, i.e. it wasn't possible to configure the selection state of a JToggleButton or JCheckboxMenuItem via an action property. Of course it was quite easy to come up with a workaround: deriving your own ToggleAction (with your custom property-firing) and complement it with view counterparts (like a ToggleAction-based JToggleButton extension) — possible, but cumbersome.

Luckily, all that clutter is no longer needed! As of 1.6, Swing supports a new Action.SELECTED_KEY. Changes to this property automatically update the selection state of JRadioButton, JCheckBox, and the like. More details (as well as a summary of all other javax.swing.Action-related changes) can be found here.

2:00 PM | Anonymous Nj said...

You learn something new every day - even when sometimes it's old news ;)

Thanks!