Netbeans Platform. How to Invoke (Call) an Action Programmatically


The Netbeans Platform (NBP) is an advanced tool for rapid application development. One of its most important features is the action. As most of the features with the NBP creating an action is straight forward using the graphical user interface. Right click a module select "Add Action", enter the required details and off you go.

In the same time it is not so clear what needs to be done to call the action from another point of your application. Lets say you have created a MenuItem action, and you want to invoke (call) it from a Toolbar action. Or from a button in your main component.

Fortunately for us this is already thought of and to be completely frank is actualy quite easy. Every action when created is required to have an identification (ID). The ID usually defines to which category the action belongs, as well as its name.

Language: Java
@ActionID(
    category = "File",
    id = "com.example.package.core.MyAction"
)

Thanks to the ID the action can be easily invoked from anywhere like this:

Language: Java
Action action = org.openide.awt.Actions.forID("File", "com.example.package.core.MyAction");
action.actionPerformed(e);

The above code will call the required action and will execute the statements defined in the actionPerformed method.