|
How do I create an Action that is automatically enabled and disabled depending on the selection |
|
|
There are three ways to do this, depending on what exactly you need:
CookieAction
CookieAction is used to write actions that are sensitive to what is in the selected Node(s) Lookup. You can specify one or more classes that must be present in the selected Node's Lookup, and some other semantics about enablement.
Being an older class, under the hood it is using Node.getCookie(), so your action will only be sensitive to things actually returned by that method - in other words, only objects that implement the marker interface Node.Cookie can work here.
NodeAction
NodeAction is somewhat more flexible, but requires more code to implement. It is just passed the array of activated nodes whenever that changes, and can choose to enable or disable itself as it wishes. Essentially this is just an action that automagically tracks the global Node selection.
Roll your own
The following is relatively simple and affords a way to perform whatever enablement logic you like (NodeAction can do that too, but this might be a little more straightforward and your code doesn't have to worry about Nodes at all). To understand how this works, see the section on the global action context:
public class FooAction extends AbstractAction implements
LookupListener, ContextAwareAction {
private Lookup context;
Lookup.Result lkpInfo;
public FooAction() {
this(Utilities.actionsGlobalContext());
}
private FooAction(Lookup context) {
putValue (Action.NAME, NbBundle.getMessage(FooAction.class,
"LBL_Action")); //NOI18N
this.context = context;
}
void init() {
assert SwingUtilities.isEventDispatchThread() :
"this shall be called just from AWT thread";
if (lkpInfo != null) {
return;
}
//The thing we want to listen for the presence or absence of
//on the global selection
Lookup.Template tpl = new Lookup.Template(Whatever.class);
lkpInfo = context.lookup (tpl);
lkpInfo.addLookupListener(this);
resultChanged(null);
}
public boolean isEnabled() {
init();
return super.isEnabled();
}
public void actionPerformed(ActionEvent e) {
init();
Collection c = lkpInfo.allItems();
//do something with them here
}
public void resultChanged(LookupEvent ev) {
setEnabled (lkpInfo.allItems().size() != 0);
}
public Action createContextAwareInstance(Lookup context) {
return new FooAction(context);
}
}
|
Source: NetBeans FAQ
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.