25

How to manage two JRadioButtons in java so that only one of them can be selected at a time? Is there any method in java to take care of this or you need to build your own logic?

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
stillStudent
  • 449
  • 2
  • 5
  • 7

2 Answers2

50

You have to add them in a ButtonGroup

ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);

Ensure you add this code after the buttons are created using the new JRadioButton constructors, as appropriate.

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44
ccheneson
  • 49,072
  • 8
  • 63
  • 68
8

My java is rusty but if i remember correctly you have to use the ButtonGroup class. Add your radio buttons to ButtonGroup object. I think it will look like this.

ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(new JRadioButton('Label', false));
buttonGroup.add(new JRadioButton('Label2', true));

Hope this helps. I have abandoned Java years ago.

uji
  • 1,603
  • 3
  • 12
  • 12
  • But then how to add them to JPanel because add method does not work for ButtonGroup – stillStudent Feb 12 '10 at 17:35
  • 4
    You still need to add the JRadioButtons to the JPanel individually; the ButtonGroup is merely a construct used to maintain the selected state of the buttons; it is not a layout component. – Adamski Feb 12 '10 at 17:41
  • sorry to bother, I figured it out in the meantime. It was exactly the way you said Adamski. Thank you. – stillStudent Feb 12 '10 at 17:43