not idle

Netbeans platform supports different kinds of actions (always enabled, CallableSystemAction, CallbackSystemAction etc). However, it was not clear to me how to create an action that could be used for toggling the state of the system. Initially, I experimented with Presenter.Menu interface and provided my own implementation of the JCheckMenuItem but couldn’t get the platform to actually invoke my method.

I finally noticed the problem. When I created the action, I created always enabled action (using the New Action wizard of course). The wizard put a number of entries to my layer.xml file. Among others, there was also the following line:

<attr name="instanceCreate"
methodvalue="org.openide.awt.Actions.alwaysEnabled"/>

causing the platform to avoid calling my getMenuPresenter implementation. Removing this line, I was finally able to get my checkbox in the menu.

But wait, Netbeans Utilities API module provides additional features. Instead of creating your own JCheckBoxMenuItem, you can use

org.openide.awt.Action.CheckboxMenuItem

Simplified example:

// Use BooleanStateAction to indicate that this action
// can toggle between two states.
public final class MyAction extends BooleanStateAction 
        implements ActionListener
{
    private final Actions.CheckboxMenuItem checkBox;
 
    public MyAction()
    {
        // initial state value
        this.setBooleanState(true);
 
        this.checkBox = new Actions.CheckboxMenuItem(this, true);
    }
 
    @Override
    public void actionPerformed(ActionEvent e)
    {
        super.actionPerformed(e);
        boolean state = getBooleanState();
 
        // Do whathever you need to do with the new state.
    }
    @Override
    public JMenuItem getMenuPresenter()
    {
        return this.checkBox;
    }
}

That’s it. You should now see your action with a checkbox in front of it.

Leave a Reply