I'd like to load a series of Swing Actions into a container at runtime and access them by a constant name as is possible with an Enum. The purpose of this would be to both restrict the Actions possible and also improve readability.
Initially, I was considering a sort of dynamic enum (see http://blog.xebia.com/2009/04/02/dynamic-enums-in-java/) but as Java Drinker points out below this is unnecessary since the actions remain unchanged.
Ideally, what I'd like to do is a sort of wrapper that contains AbstractAction
instances which could be enabled/disabled and be able to refer to each action through a symbolic name.
Edit: Question has been reformulated.
You can do something like this:
public enum Actions {
COPY( new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//do something
}
}),
PASTE( new PasteAction() );
public final AbstractAction action;
private Actions(AbstractAction action) {
this.action = action;
}
}
//...
Actions.COPY.action...;
And then as others have said, use the enum in conjunction with an EnumSet or EnumMap. Personally, I don't see a huge value in it over just having a few named fields without an enum.
I think what you really want is some kind of Action registry like this:
public class ActionsManager {
private final Map<String, Action> actions;
private final Map<User, Set<String>> enabledActions;
public Action get(String id);
public void register(String id, Action action);
public void deregister(String id);
public boolean isEnabled(User user, Action action);
}
Implementation left as an exercise.