Managing Swing Actions with a Registry
action, java, swing, user-interface
Solution
Jeff, your approach seems like a good approach. I do the same thing. I call the registry ActionHandler and it looks like this:
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableClassToInstanceMap;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
public class ActionHandler {
private static final ClassToInstanceMap<Action> actionMap =
new ImmutableClassToInstanceMap.Builder<Action>().
put(DefaultEditorKit.CutAction.class, new DefaultEditorKit.CutAction()).
put(DefaultEditorKit.CopyAction.class, new DefaultEditorKit.CopyAction()).
put(DefaultEditorKit.PasteAction.class, new DefaultEditorKit.PasteAction()).
put(RefreshAction.class, new RefreshAction()).
put(MinimizeAction.class, new MinimizeAction()).
put(ZoomAction.class, new ZoomAction()).
build();
public static Action getActionFor(Class<? extends Action> actionClasss) {
return actionMap.getInstance(actionClasss);
}
}
Now to disable, say ZoomAction, I use
ActionHandler.getActionFor(ZoomAction.class).setEnabled(false);
Problem
Typically when I'm creating a Swing (or any UI) application, I have various Actions that appear on menu items and buttons. I usually create an action registry and store the actions in there and then when certain things occur, I disable/enable actions in the registry based on the state of the application. I wouldn't call myself an avid Swing developer, although I know my way around it well enough, but is this a pretty typical pattern for managing Actions? Or is there a more standard way of doing it? thanks, Jeff