Disable group of radio buttons

10,808

Solution 1

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);
}

Solution 2

A simple solution would be to place the buttons in an array...

    JRadioButton[] buttons = new JRadioButton[]{jbutton1,jbutton2,jbutton3,jbutton4};

The iterate the array and change the state of the buttons...

    for (JRadioButton btn : buttons) {
         btn.setEnabled(false);
    }

Or you can enter the radio button group in a JPanel and add that JPanel.

On OK Button click event you can get the components and iterate through the loop to disable them.

   for(Component c:jpanel1.getComponents()){
        c.setEnabled(false);
   }
Share:
10,808
Christian
Author by

Christian

Updated on June 04, 2022

Comments

  • Christian
    Christian almost 2 years

    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.

  • Hovercraft Full Of Eels
    Hovercraft Full Of Eels almost 10 years
    1+ @Christian: if this answer answered your question, please accept it by clicking on the large check mark to the left of it. This way you can give the poster (who looks like changed his name? Braj?) 15 rep points
  • Braj
    Braj almost 10 years
    @Christian are you kidding with me. :)