Over a million developers have joined DZone.

NetBeans Platform Tip: BooleanStateActions

· Java Zone

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

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 JetBrains.  Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}