How to select only one radio button?

3

In Java swing, a user can select more than one radio button simultaneously, so that it does not happen, one can do:

private void radio1ActionPerformed(java.awt.event.ActionEvent evt) {
    if (radio1.isSeleced()) {
        radio2.isSelected(false);
    }
}

But this is very impractical, imagine a situation that requires dozens of radio buttons, it would be too much trouble.

Is there any other way to do what I want? I thought about using a foreach by putting all the radio buttons inside a vector, but I could not abstract anything.

    
asked by anonymous 11.10.2014 / 18:02

1 answer

9

The solution to this is to use javax.swing.ButtonGroup , which allows you to group the javax.swing.JRadioButton into groups.

Example:

...
buttonGroup1 = new javax.swing.ButtonGroup();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();

buttonGroup1.add(jRadioButton1);
buttonGroup1.add(jRadioButton2);
buttonGroup1.add(jRadioButton3);
...

It can be used with any other component that inherits the AbstractButton class according to the documentation here .

    
11.10.2014 / 18:11