Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

NetBeans Platform Tip: BooleanStateActions

DZone's Guide to

NetBeans Platform Tip: BooleanStateActions

· Java Zone ·
Free Resource

Learn how to build stream processing applications in Java-includes reference application. Brought to you in partnership with Hazelcast.

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

Learn how to build distributed stream processing applications in Java that elastically scale to meet demand- includes reference application.  Brought to you in partnership with Hazelcast.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}