JToggleButton.One selected, others deselected

1k views Asked by At

So I have three buttons, let's say 1, 2 and 3. I want, when I click button1, button2 and button3 to be deselected. After, when I click button2, I want button1 and button3 to be deselected. Same for button3.

Basically, when I click one button, I want the other 2 to be deselected. So far I have the following code but I'm stuck somewhere and I can't see the mistake.

if(smallbuttonpage1.isSelected()){
    normalbuttonpage1.setSelected(false);
    bigbuttonpage1.setSelected(false);
    textpage1.setFont(new Font("ComicSansMS", Font.PLAIN, 8));
}
if(normalbuttonpage1.isSelected()){
    smallbuttonpage1.setSelected(false);
    bigbuttonpage1.setSelected(false);
    textpage1.setFont(new Font("ComicSansMS", Font.PLAIN, 12));
}
if(bigbuttonpage1.isSelected()){
    smallbuttonpage1.setSelected(false);
    normalbuttonpage1.setSelected(false);
    textpage1.setFont(new Font("ComicSansMS", Font.PLAIN, 20));
}
2

There are 2 answers

0
Hauke Ingmar Schmidt On BEST ANSWER

You simply add all buttons to a newly created ButtonGroup. This automatically takes care for deselecting the other buttons.

Have a look into the Swing tutorial: http://docs.oracle.com/javase/tutorial/uiswing/components/button.html#radiobutton

1
MrSilent On

I figured it out in the end. I used hasFocus() instead of isSelected() and it works just fine, hope it helps anyone in the future.