0

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));
}
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
MrSilent
  • 564
  • 10
  • 28
  • 3
    can you describe what being "stuck" means, what exactly is going wrong? i would also recommend JRadioButton within a button group for this. – Neil Locketz Jan 06 '14 at 23:03
  • Stuck as in, when I click button2 when button1 is selected, button1 does not isSelected(false). – MrSilent Jan 06 '14 at 23:04

2 Answers2

5

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

Hauke Ingmar Schmidt
  • 11,559
  • 1
  • 42
  • 50
0

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.

MrSilent
  • 564
  • 10
  • 28
  • No, don't. This is a horrible idea. You have no means to guarantee that the focus will remain with the button, also you will have no means to inspect the result in the future... – MadProgrammer Jan 06 '14 at 23:54