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.
Asked
Active
Viewed 8,139 times
10
-
2That 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? – Luis Miguel Serrano Feb 05 '11 at 00:05
5 Answers
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();
}
}
}

remi
- 3,914
- 1
- 19
- 37
-
1Or an anonymous inner class will suffice, e.g., `ButtonGroup myGroup = new ButtonGroup(){ /*code from above*/ };` – captainroxors May 19 '14 at 17:18
-
@MarkJeronimus [answer](https://stackoverflow.com/a/22227537/2506021) refines this to avoid clearing the selection calling `button.setSelected(false)` on a button/checkbox that is not selected. – Rangi Keen Apr 29 '19 at 18:57
5
This shows exactly how to do that https://dzone.com/articles/unselect-all-toggle-buttons

Emmanuel Bourg
- 9,601
- 3
- 48
- 76

Jeff Storey
- 56,312
- 72
- 233
- 406
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();
}
}
}

Mark Jeronimus
- 9,278
- 3
- 37
- 50
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.

Stalin Gino
- 592
- 9
- 28
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);
}
}

Padde
- 26
- 3