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.

Humayun Shabbir
  • 2,961
  • 4
  • 20
  • 33
Christian
  • 991
  • 2
  • 13
  • 25
  • 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... – JB Nizet Jul 27 '14 at 12:06
  • wrong post.. that was for other question@JBNizet – Deepanshu J bedi Jul 27 '14 at 12:11
  • 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. – jpw Jul 27 '14 at 12:13

2 Answers2

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);
}
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 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 – Hovercraft Full Of Eels Jul 27 '14 at 13:28
  • @Christian are you kidding with me. :) – Braj Jul 30 '14 at 09:52
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);
   }
Aniruddha Sarkar
  • 1,903
  • 2
  • 14
  • 15