Search code examples
javaswingnetbeansactionnetbeans-plugins

Actions in NetBeans module - context menu, main menu


I am developing NetBeans module and I have declared an action (using annotations, they are translated to layer.xml record) which works with my custom project type (EsperProject class):

@ActionID(category = "Run", id = "my.package.RunEsperAction")
@ActionRegistration(displayName = "My Action", asynchronous=true)
@ActionReferences({
    @ActionReference(path = "Menu/BuildProject", position = 0)
})
public final class RunEsperAction implements ActionListener {

    private final EsperProject project;

    public RunEsperAction(EsperProject project) {
        this.project = project;
    }

    @Override
    public void actionPerformed(ActionEvent ev) {
       // do sth with project
    }
}

I can run the action from the BuildProject Menu (which is actualy Run menu), but i CANNOT make it work in two cases I need (both called asynchronously as declared in the annotation):

  1. I'd like to run the action from the project context menu.
  2. I need to have the action triggered when my EsperProject is run from the main menu item "Run Main Project".

Thanks for any suggestions.


Solution

  • I have figured out the first point: To run the action from the context menu, we must add it to the getActions() method of the project root node, something like this:

    class RootNode extends FilterNode {
        @Override
        public Action[] getActions(boolean arg0) {
            List<Action> nodeActions = new ArrayList<Action>();
            nodeActions.addAll(Utilities.actionsForPath("Actions/MyCategoryInLayer"));
            return nodeActions.toArray(new Action[nodeActions.size()]);
        }
    }
    

    The action appears in the context menu of the project and is run asynchronously. However, overriding "Run main project" is still imposible for me. I try the simmilar aproach but this fails:

    @Override
    public void invokeAction(String actionName, Lookup lookup) throws IllegalArgumentException {
    
    if (actionName.equalsIgnoreCase(ActionProvider.COMMAND_RUN)) {
        List<? extends Action> runActions = Utilities.actionsForPath("Actions/Run");
            for (Action action : runActions) {
                action.actionPerformed(null);
            }
    }
    

    with

    java.lang.NullPointerException at org.openide.util.actions.ActionInvoker$ActionRunnable.needsToBeSynchronous(ActionInvoker.java:147)