Platinum Partner
netbeans,netbeans platform,tip

NetBeans Platform Tip: BooleanStateActions

If you want to have an action that changes flag state using toobar button or menu check, you can use BooleanStateActions.

Create ChangeStateAction using wizard dialog with menu and toolbar buttons.

Here is the generated code:

public final class ChangeStateAction extends CallableSystemAction
{

public void performAction()
{
// TODO implement action body
}

public String getName()
{
return NbBundle.getMessage(ChangeStateAction.class, "CTL_ChangeStateAction");
}

@Override
protected String iconResource()
{
return "com/antilogics/binary.png";
}

public HelpCtx getHelpCtx()
{
return HelpCtx.DEFAULT_HELP;
}

@Override
protected boolean asynchronous()
{
return false;
}
}

Replace CallableSystemAction class with BooleanStateAction, remove "performAction" and "asynchronous" methods. Add following code:

    private JToggleButton toggleButton;
private JCheckBoxMenuItem menuButton;


public ChangeStateAction()
{
// initial state value
setBooleanState(true);

toggleButton = new JToggleButton();
Actions.connect(toggleButton, this);
menuButton = new JCheckBoxMenuItem(getName());
Actions.connect(menuButton, this);
}


@Override
public void actionPerformed(ActionEvent event)
{
super.actionPerformed(event);
boolean state = getBooleanState();
// do something with new state...
}


// replace toolbar button with yours
@Override
public Component getToolbarPresenter()
{
return toggleButton;
}

// replace menu item with yours
@Override
public JMenuItem getMenuPresenter()
{
return menuButton;
}


Here is the result:

That's all! Enjoy

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}