How to create ButtonGroup of JToggleButton's that allows to deselect the actual option?
Asked Answered
V

5

10

That's it. I need to create a ButtonGroup that allows to select a option or, if the user click on the selected option, deselect the item (nothing will be selected) and, of course, capture the event to do something.

Violence answered 4/2, 2011 at 23:56 Comment(1)
That might not be intuitive for the user. Have you thought about making one option to represent the state/choice that would correspond to the deselection?Proper
P
13

Just in case Jeff's link is broken in the future, here's what's described: you need to subclass ButtonGroup to allow a no-selection, and add your buttons to this buttongroup.

public class NoneSelectedButtonGroup extends ButtonGroup {

  @Override
  public void setSelected(ButtonModel model, boolean selected) {
    if (selected) {
      super.setSelected(model, selected);
    } else {
      clearSelection();
    }
  }
}
Phenice answered 24/5, 2013 at 9:34 Comment(2)
Or an anonymous inner class will suffice, e.g., ButtonGroup myGroup = new ButtonGroup(){ /*code from above*/ };Leavenworth
@MarkJeronimus answer refines this to avoid clearing the selection calling button.setSelected(false) on a button/checkbox that is not selected.Identity
S
5

This shows exactly how to do that https://dzone.com/articles/unselect-all-toggle-buttons

Script answered 5/2, 2011 at 1:26 Comment(0)
B
1

I noticed weird behavior when doing button.setSelected(false) on a button/checkbox that is not selected. It deselected everything as if I deselected something.

I fixed it this way:

public class NoneSelectedButtonGroup extends ButtonGroup {

  @Override
  public void setSelected(ButtonModel model, boolean selected) {
    if (selected) {
      super.setSelected(model, selected);
    } else if (getSelection() != model) {
      clearSelection();
    }
  }
}
Brumby answered 6/3, 2014 at 14:35 Comment(0)
S
0

Capture the event to do something. Also do the below.

@Override
public void actionPerformed(ActionEvent e) {
    ((JToggleButton)e.getSource()).setSelected(false);
}

EDIT: But there is no ButtonGroup involved.

Selfrespect answered 2/6, 2013 at 3:20 Comment(0)
P
0

Solution for pre java 1.6

public class NoneSelectedButtonGroup extends ButtonGroup {
    private AbstractButton hack;

    public NoneSelectedButtonGroup() {
        super();
        hack = new JButton();
        add(hack);
    }

    @Override
    public void setSelected(ButtonModel model, boolean selected) {
        super.setSelected(selected ? model : hack.getModel(), true);
    }
}
Puebla answered 2/3, 2014 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.