Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 602
Christian Avatar asked Jul 27 '14 12:07

Christian


2 Answers

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);
}
like image 175
Braj Avatar answered Sep 22 '22 05:09

Braj


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);
   }
like image 33
Aniruddha Sarkar Avatar answered Sep 23 '22 05:09

Aniruddha Sarkar