javaswingbuttongroup

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.


Solution

  • 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();
        }
      }
    }