Search code examples
javaswingawtjradiobuttonbuttongroup

Disable group of radio buttons


I have a group of radio buttons defined as 'ButtonGroup bg1;' using 'javax.swing.ButtonGroup' package. I would like to disable this group so that the user cannot change their selection after clicking the OK-button 'btnOK'.

So I was looking for something along these lines:

private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {
   bg1.setEnabled(false);
}

However, .setEnabled(false) does not seem to exist.


Solution

  • I would like to disable this group

    ButtonGroup is not a visual component. It is used to create a multiple-exclusion scope for a set of buttons.

    Creating a set of buttons with the same ButtonGroup object means that turning "on" one of those buttons turns off all other buttons in the group.


    You have to disable each and every JRadioButton added in Buttongroup because ButtonGroup doesn't have any such method to disable whole group.

    Sample code:

    Enumeration<AbstractButton> enumeration = bg1.getElements();
    while (enumeration.hasMoreElements()) {
        enumeration.nextElement().setEnabled(false);
    }