Hannibal
Hannibal

Reputation: 15

How to disable a JRadioButton inside a ButtonGroup in Java

i have four JRatioButtons inside a ButtonGroup in Java. The two first are enabled and the other two are disabled. If one specific JRatioButton is selected i need to enable the two disabled JRatioButtons.

Im trying this to find the state of the buttons and enable the disabled ones, apparently i found the ones with the disable state but doesnt change that state.

private void activateButtons() {
    Enumeration<AbstractButton> elements = myButtonGroup.getElements();
    while (elements.hasMoreElements()) {
          AbstractButton button = (AbstractButton)elements.nextElement();
          if (button.isEnabled()) {
            System.out.println("This button is disabled! The text of the button is: '" + button.getText() + "'");
            button.setEnabled(true);
          }
    }
}

Im getting the text of the disabled buttons, but i cant disable them.

Any help? Thanks!

Upvotes: 0

Views: 14590

Answers (3)

sky91
sky91

Reputation: 3180

Ya, you setEnabled(true) to an enabled RadioButton.
So here the edited, hope can help someone.

private void activateButtons() 
{
    Enumeration<AbstractButton> elements = myButtonGroup.getElements();
    while (elements.hasMoreElements()) 
    {
          AbstractButton button = (AbstractButton)elements.nextElement();
          if (button.isEnabled())     // if enabled (true) 
          {
            System.out.println("This button is disabled! The text of the button is: '" + button.getText() + "'");
            button.setEnabled(false); // set it disabled (false)
          }
    }
}

Thanks @Hannibal, your post saved my day.

Upvotes: 0

Yasas
Yasas

Reputation: 82

Try this, it works.

AbstractButton button = ...

button.getModel().setEnabled(true/false)

Upvotes: 1

seanxiaoxiao
seanxiaoxiao

Reputation: 1302

I don't know if you any problems in finding the reference of the radio buttons in the second group or you just cannot disable the radio buttons.

For the first question, it is simple, you just keep the reference of the radio buttons in the second group.

For the second question, you need to subclass a JRadioButton because I found you can not simply call disable for an object of radio button.

The code sample of the sub class would be like this.

this.editable = editable;
if (editable) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    super.enableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
} else {
    this.setCursor(CursorFactory.createUnavailableCursor());
    super.disableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
}

Upvotes: 1

Related Questions