Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 854
jion Avatar asked Feb 04 '11 23:02

jion


2 Answers

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();
    }
  }
}
like image 60
remi Avatar answered Nov 15 '22 11:11

remi


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();
    }
  }
}
like image 24
Mark Jeronimus Avatar answered Nov 15 '22 10:11

Mark Jeronimus