How to select only one radio button?

Asked

Viewed 9,074 times

3

In the swing of Java, a user can select more than one radio button simultaneously, so this 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 work.


Is there any other way to do what I wish? I thought I’d use one foreach putting all radio buttons inside a vector, but I couldn’t abstract anything.

  • 2

    Aren’t you forgetting to group the JRadioButton in a ButtonGroup No? The standard behavior of a Radiobutton in a Group is to keep only one selected.

1 answer

9


The solution to this is the use of javax.swing.ButtonGroup which makes it possible to group the components into groups javax.swing.JRadioButton.

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 class AbstractButton as documented here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.