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-thought 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();
}
}
}Note: clearSelection() is available only since Java 6
From http://blog.frankel.ch/unselect-all-toggle-buttons-of-a-group
- Login or register to post comments
- 4350 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)




Comments
Mihai Dinca-pan... replied on Tue, 2010/08/10 - 3:58am
Yes. I had this problem long ago, previous to java 1.6 and clearSelection was not there.
The solution is to have an invisible radio button inside the group. Deselecting all radio buttons means selecting the invisible one