2.8.10

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

There are several ways to do this, depending on what exactly you need. The basic problems all of the available solutions are addressing is that:

  • An action may be created and shown in a menu, toolbar or popup menu.
  • While it is visible on-screen, the selected file (or whatever) can change.
  • If it is context sensitive, it should run against the thing it was shown for not whatever is selected at the millisecond when it is actually called
  • People want to write main-menu and toolbar actions which are enabled and disabled based on what is selected - in practice this means writing an object that enables and disables itself based on a particular type — a particular class or its subclasses — being selected (each logical window in NetBeans has its own "selection"; the "global selection" is whatever is selected in whatever window currently has focus)

NetBeans 6.9 allows context-sensitive actions to be registered declaratively in your module'sXML layer file. In the IDE, File > New File > Module Development > Action will generate some rather opaque layer-based registration code for you (on the first page of the wizard, specify that you want a context sensitive action):

    <file name="mypackage-SomeAction.instance">
<attr name="delegate" methodvalue="org.openide.awt.Actions.inject"/>
<attr name="displayName" bundlevalue="mypackage.Bundle#CTL_SomeAction"/>
<attr name="injectable" stringvalue="mypackage.SomeAction"/>
<attr name="instanceCreate" methodvalue="org.openide.awt.Actions.context"/>
<attr name="noIconInMenu" boolvalue="true"/>
<attr name="selectionType" stringvalue="ANY"/>
<attr name="type" stringvalue="org.netbeans.api.project.Project"
/>
</file>

and a somewhat inscrutable ActionListener implementation

 public final class SomeAction implements ActionListener {
private final List<Project> context;
public SomeAction(List<Project> context) {
this.context = context;
}
public void actionPerformed(ActionEvent ev) {
for (Project project : context) {
// TODO use project
}
}
}

which will be called if and only if one or more projects is selected. The good news is that the code is lightweight, simple and works; the bad news is that it is utterly non-obvious how it ever gets called, and doesn't handle more complicated enablement logic.

If you need something more featureful, there are a few options, old and new:


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: 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() {
this(Utilities.actionsGlobalContext());
}   private FooAction(Lookup context) {
putValue(Action.NAME, NbBundle.getMessage(FooAction.class, "LBL_Action"));
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
lkpInfo = context.lookupResult(Whatever.class);
lkpInfo.addLookupListener(this);
resultChanged(null);
}   public boolean isEnabled() {
init();
return super.isEnabled();
}   public void actionPerformed(ActionEvent e) {
init();
for (Whatever instance : lkpInfo.allInstances()) {
// use it somehow...
}
}   public void resultChanged(LookupEvent ev) {
setEnabled(!lkpInfo.allInstances().isEmpty());
}   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 (but is not) 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.


Not-Yet-Official spi.actions

This module is part of the platform as of 6.8, but has not yet become official API. Nonetheless it is there, it is stable and straightforward to use. The example below opens a visual editor window if an instance of RAFDataObject is selected and has a RandomAccessFile in its lookup:

public final class CustomOpenAction extends org.netbeans.spi.actions.Single<RAFDataObject>
{
public CustomOpenAction() {
super(RAFDataObject.class, "Open", null);
}
@Override
protected void actionPerformed(RAFDataObject target) {
//If an editor is already open, just give it focus
for (TopComponent tc : TopComponent.getRegistry().getOpened()) {
if (tc instanceof RAFEditor && tc.getLookup().lookup(RAFDataObject.class) == target) {
tc.requestActive();
return;
}
}
//Nope, need a new editor
TopComponent editorWindow = null;
editorWindow = new RAFEditor(target);
editorWindow.open();
editorWindow.requestActive();
}
@Override
protected boolean isEnabled(RAFDataObject target) {
//Make sure there really is a file on disk
return target.getLookup().lookup(RandomAccessFile.class) != null;
}
}

Use ContextAction instead of Single to create actions that operate on multi-selections.

 


http://wiki.netbeans.org/DevFaqActionContextSensitive

No comments: