NB: How to create a context sensitive action within a submenu

Today somebody asked “how create a context sensitive action with a submenu in the project-view?” in the NetBeans mailing list. So I figured it out and I like to document it using this post.

First here is the action for the submenu. The action is registered to the project context menu. It uses the Presenter.Popup interface to register itself as a submenu. In the getPopupPresenter() method the submenu is assembled via Utilities.actionsForPath.

        category = "MyActions",
        id = "de.markiewb.netbeans.sample.PopupAction"
        displayName = "#CTL_PopupAction", lazy = false
    @ActionReference(path = "Projects/Actions")
@Messages("CTL_PopupAction=I am a submenu")
public final class PopupAction extends AbstractAction implements ActionListener, Presenter.Popup {

    public void actionPerformed(ActionEvent e) {

    public JMenuItem getPopupPresenter() {
        JMenu main = new JMenu(Bundle.CTL_PopupAction());
        List<? extends Action> actionsForPath = Utilities.actionsForPath("Actions/MyActions/SubActions");
        for (Action action : actionsForPath) {
        return main;

In the previous code snippet Utilities.actionsForPath has been used to resolve action(s) at Actions/MyActions/SubActions. Here is a context sensitive action, which is registered at this location.

        category = "MyActions/SubActions",
        id = "de.markiewb.netbeans.sample.HelloProjectsAction"
        displayName = "#CTL_HelloProjectsAction"
public final class HelloProjectsAction implements ActionListener {

    private final List context;

    public HelloProjectsAction(List context) {
        this.context = context;

    public void actionPerformed(ActionEvent ev) {
        JOptionPane.showMessageDialog(null, context.size() + " projects selected: " + context);

The result:

The complete sample code can be found at https://github.com/markiewb/nb-api-samples/tree/master/SubmenuWithContextSensitiveAction. I will also add this documentation to the offical developer FAQ at http://wiki.netbeans.org/DevFaqActionNodePopupSubmenu

Happy coding!

Update: The second part of this post can be found at https://benkiew.wordpress.com/2015/09/13/nb-how-to-create-a-context-aware-submenu/


3 thoughts on “NB: How to create a context sensitive action within a submenu

  1. Pingback: NB: How to create a context sensitive action within a submenu | Dinesh Ram Kali.

  2. Pingback: NB: How to create a context-aware submenu | markiewb's blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s