How do I add an action to a project popup menu of a specific project type?
Note: These pages are being reviewed.
Generic approach
You can install an action into the context menu of all projects simply by adding to your layer under the folder Projects/Actions/
. Your action should be context-sensitive, meaning it should be a placeholder which implements ContextAwareAction
; the context-aware derived action will do the real work. Generally it will look for an instance of Project
in the supplied Lookup
(context).
If you just override isEnabled
on the derived action based on the context, the menu item will always be present, though it will be greyed out in the case of inappropriate projects. If you want to hide the menu item for all but relevant projects, you need to set an additional flag (available starting in 6.9).
The following trivial action shows the location of a project so long as its name comes in the first half of the alphabet:
@ActionID(...)
@ActionRegistration(...)
@ActionReference(path="Projects/Actions")
public class DemoAction extends AbstractAction implements ContextAwareAction {
public @Override void actionPerformed(ActionEvent e) {assert false;}
public @Override Action createContextAwareInstance(Lookup context) {
return new ContextAction(context);
}
private static final class ContextAction extends AbstractAction {
private final Project p;
public ContextAction(Lookup context) {
p = context.lookup(Project.class);
String name = ProjectUtils.getInformation(p).getDisplayName();
// TODO state for which projects action should be enabled
char c = name.charAt(0);
setEnabled(c >= 'A' && c <= 'M');
putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true);
// TODO menu item label with optional mnemonics
putValue(NAME, "&Info on " + name);
}
public @Override void actionPerformed(ActionEvent e) {
// TODO what to do when run
String msg = "Project location: "
+ FileUtil.getFileDisplayName(p.getProjectDirectory());
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg));
}
}
}
Specific approach
Certain project types also read their context menu actions from type-specific folders.
For example
<ul>
<li>Maven: Projects/org-netbeans-modules-maven/Actions
</li>
</ul>
Applies to: NetBeans 7.0+