Revision as of 15:48, 2 December 2009 by Rmichalsky (Talk | contribs)

How do I create an Action that is automatically enabled and disabled depending on the selection?

There are two ways to do this, depending on what exactly you need:


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: DevFaqWhatIsANode). To understand how this works, see DevFaqTrackGlobalSelection:

public class FooAction extends AbstractAction implements LookupListener, ContextAwareAction {
    private Lookup context;
    Lookup.Result<Whatever> lkpInfo;

    public FooAction() {

    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) {

        //The thing we want to listen for the presence or absence of
        //on the global selection
        lkpInfo = context.lookupResult(Whatever.class);

    public boolean isEnabled() {
        return super.isEnabled();

    public void actionPerformed(ActionEvent e) {
        Collection<? extends Whatever> 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);

Deprecated CookieAction

In many older (pre-NB 6.8) examples you may find CookieAction. It should be currently deprecated, the original info is left here for reference and/or old code maintenance:

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.

Applies to: NetBeans 6.5 and above

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo