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.
How to create ButtonGroup of JToggleButton's that allows to deselect the actual option?
8.2k views Asked by jion At
5
There are 5 answers
0
On
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);
}
}
0
On
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();
}
}
}
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.