So, I don't know if this is overly complicated, but (since I like enums
for things like this) we implemented something like this:
public enum Actions
{
OPEN_FILE {
@Override
public void perform(ContextInfo contextInfo) {
// do the work here
}
},
CLOSE_FILE {
etc.
// Custom method that is implemented by each action to perform its
work
public abstract void perform(ContextInfo contextInfo);
}
Then I made my custom action class that takes one of these enums as a
parameter and does the self-registration at construction time:
public class CustomAction extends org.apache.pivot.wtk.Action
{
private Actions action;
public CustomAction(Actions action, boolean enabled) {
this.action = action;
// Register ourselves with the named action dictionary in
the application
Action.getNamedActions().put(action.toString(), this);
setEnabled(enabled);
}
@Override
public void perform(Component comp) {
ContextInfo contextInfo = new ContextInfo();
// derive the context from the given component
...
this.action.perform(contextInfo);
}
...
As Todd indicated, each CustomAction also deals with its
enabled/disabled state like this:
public static CustomAction getAction(Actions a) {
return (CustomAction)
Action.getNamedActions().get(a.toString());
}
public static boolean isEnabled(Actions a) {
return getAction(a).isEnabled();
}
public static void setEnabled(Actions a, boolean enabled) {
getAction(a).setEnabled(enabled);
}
So that I can write code (using my enum so I don't misspell the names)
like this:
CustomAction.setEnabled(Actions.OPEN_FILE, true);
Also, if there is ever a need to perform an action explicitly, you can
do this:
CustomAction.getAction(Actions.SAVE_FILE).perform(/* component
here */);
Then finally, in the "startup" method of the main class, I do this to
register all the actions:
for (Actions a : Actions.values()) {
new CustomAction(a);
}
HTH,
~Roger Whitcomb
From: Cynthia Schwartz [mailto:[email protected]]
Sent: Wednesday, May 29, 2013 8:27 AM
To: [email protected]
Subject: registering actions as event listeners on the app
Awhile back Todd wrote :
Action is a higher level abstraction that at the event handler level.
For instance, I have things like NewInvoiceAction, DeleteInvoiceAction,
ProvideFeedbackAction, etc. They each register themselves as event
listeners on the app and maintain an internal state -- thus allowing
them to perform their action at any time without needing to know how
they were triggered. They also maintain their own enabled/disabled
state in a similar fashion. Then I wire up my buttons, menus, and
keystrokes to my actions, and my get auto-disabling of those buttons and
menu items for free.
Can someone provide an example of them rgister themselves as event
listeners on the app?
Thanks.
C