Over a million developers have joined DZone.
Gold Partner

NetBeans Platform Tip: BooleanStateActions

· Java Zone

The Java Zone is brought to you in partnership with Azul Systems.   Discover how to stop tuning and get back to coding with Azul Zing.

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

The Java Zone is brought to you in partnership with Azul Systems.   Discover how to stop tuning and get back to coding with Azul Zing.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}