Unselect all toggle buttons of a group

It’s summer and since I’m hearing more and more the sound of waves splashing instead of the sound of keyboards typing, I’m providing you with quick tricks instead of well-though deep articles.

This time, it’s about Swing. I’m doing Swing for a pet project…​ a lot. And I’m more of a web guy. So, I’m always butting my head against the wall trying to overcome problem people more experienced in Swing wouldn’t find a problem at all. This is good, since it teaches me another way too think (I as a web developer am not so much event-based, but it is coming to a change with frameworks such as Vaadin or standards like CDI).

This said, my latest problem was the following. Most of the time, the toggle buttons are radio buttons: you programmatically select one radio before screen display and since all radios are in the same ButtonGroup, when the user selects one, it deselects the one previously selected. This is good but what if my default state would be that no radio be selected?

In fact, to always select a radio means the default state should be displayed as a radio like the others. In my project, I want the default state to be no radio selected, but keep the classical behaviour where selecting a radio means deselecting the one before. Using Swing default classes, it doesn’t work, even if you replace the radio buttons by toggle buttons: when one is selected, it stays selected. Looking at the ButtonGroup code, one understands why:

public void setSelected(ButtonModel m, boolean b) {
  if (b && m != null && m != selection) {
    ButtonModel oldSelection = selection;
    selection = m;
    if (oldSelection != null) {
      oldSelection.setSelected(false);
    }
    m.setSelected(true);
  }
}

The classical ButtonGroup only manages when the state goes from unselected to selected! This is cool when using radio buttons, not so with toggle buttons.

In order to potentially have no selected buttons in your group, use the following class instead of ButtonGroup:

public class NoneSelectedButtonGroup extends ButtonGroup {
  @Override
  public void setSelected(ButtonModel model, boolean selected) {
    if (selected) {
      super.setSelected(model, selected);
    } else {
      clearSelection();
    }
  }
}
clearSelection() is available only since Java 6
Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Unselect all toggle buttons of a group
Share this