Darakath Darakath - 2 months ago 18
Java Question

How to randomly select a button in a ButtonGroup of JRadioButtons?

I want to have a random radio button to be selected whenever this panel gets initialized, but I'm not sure how/if I can do that.

Is there a way to get a random button from the group and select it?

import javax.swing.*;

public class RandomPanel extends JPanel
{
private ButtonGroup buttonGroup;
private String[] buttonText =
{
"Red",
"Mashed Potatoes",
"Metal",
"Running",
"Butts",
"Turquoise"
};

public RandomPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createTitledBorder("Random Selections"));

buttonGroup = new ButtonGroup();
for (String text : buttonText)
{
JRadioButton option = new JRadioButton(text);
add(option);
button.add(option);
}
}

}

Answer

What you can do is keep a list/array of all the radio buttons you create, and then set the selected by using the button group's setSelected() method, something like this

buttonGroup.setSelected(buttonsArray[randomButtonNum].getModel(), true);
Comments