Disable group of radio buttons
Asked Answered
I

2

6

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.

Infiltrate answered 27/7, 2014 at 12:4 Comment(3)
Yep. So what's your question? What could you possibly do to disable all the radio buttons of the group? Maybe... disable all the radio buttons of the group...Dorinedorion
wrong post.. that was for other question@JBNizetPrince
The ButtonGroup class has a method getElements that returns an enumeration of buttons in the group. Iterate over that and call setEnabled(false) on each button.Laevorotation
R
9

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);
}
Rufusrug answered 27/7, 2014 at 12:13 Comment(2)
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 pointsSy
@Infiltrate are you kidding with me. :)Rufusrug
V
1

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);
   }
Volnay answered 27/7, 2014 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.