简体   繁体   English

如何在JRadioButtons的ButtonGroup中随机选择一个按钮?

[英]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);
        }
    }

}

您可以做的是保留所有创建的单选按钮的列表/数组,然后使用按钮组的setSelected()方法设置所选内容,如下所示

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

Try using the Random class . 尝试使用Random类。

    // Library location
    import java.util.Random;

    //Inside some method
    Random r = new Random();
    randomIndex = r.nextInt(buttonText.length());
    text = buttonText[randomIndex];

This will need arranging to suit your implementation, whats shown is a 'how-to' usage. 这将需要安排以适合您的实现,显示的是“如何”用法。

Note: the argument to nextInt(args) is exclusive. 注意: nextInt(args)是唯一的。 ie will return 0 <= x < args 即将返回0 <= x < args

I believe you are looking for something like the solution below. 我相信您正在寻找类似下面的解决方案。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

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

    private JRadioButton[] radioButton;

    Random r = new Random();

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

        buttonGroup = new ButtonGroup();

        radioButton = new JRadioButton[buttonText.length];

        for(int rb=0; rb<buttonText.length; rb++)
        {
            radioButton[rb] = new JRadioButton(buttonText[rb]);
            add(radioButton[rb]);
            buttonGroup.add(radioButton[rb]);
        }

        JButton b = new JButton("Random");
        b.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                selectRandomButton();
            }
        });

        add(b);
    }

    public void selectRandomButton()
    {
        radioButton[r.nextInt(radioButton.length)].setSelected(true);
    }

    public static void main(String[] args)
    {
        JFrame f = new JFrame("Test Random Button");
        f.setSize(300, 300);
        f.setLocationRelativeTo(null);;
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.add(new RandomPanel());

        f.setVisible(true);;
    }
}

I created a small method that allow me to set any radio group button. 我创建了一个小方法,可以设置任何单选按钮。 Very convenient if you don't want to use if for any radio button. 如果您不想使用任何单选按钮,则非常方便。

public void setButtonGroup(int rdValue, Enumeration elements ){
    while (elements.hasMoreElements()){
        AbstractButton button = (AbstractButton)elements.nextElement();
        if(Integer.parseInt(button.getActionCommand())==rdValue){
            button.setSelected(true);
        }
    }
}

then 然后

setButtonGroup(randomIndex, yourButtonGroup.getElements());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ButtonGroup中使用4个JRadioButton,使用数字值选择特定的按钮 - 4 JRadioButtons used in a ButtonGroup, selecting specific button with a numeric value 如何启用/禁用按钮而不是选择它? (按钮组) - How to enable/disable button instead of select it ? (buttongroup) 将JRadioButtons放在ButtonGroup的新行中? - Put JRadioButtons in new rows in ButtonGroup? 如何在Java中添加面板中的JRadioButtons按钮组或仅添加面板中的JRadioButtons按钮组? - How to add a button group of JRadioButtons in a Panel or just JRadioButtons in a panel in Java? 如何为在一个循环中创建其所有JRadioButton的ButtonGroup设置setSelected? - How can I setSelected for a ButtonGroup where all its JRadioButtons were created in a loop? 如何选择多个JCheckBoxe到ButtonGroup中? - How to select multiple JCheckBoxe into ButtonGroup? 如何从ButtonGroup中选择JRadioButton? - How to select a JRadioButton from ButtonGroup? 如何在 Java 中取消选择 ButtonGroup 中的单选按钮选项? - How to deselect the radio button options in a ButtonGroup in Java? 在JRadioButtons的ButtonGroup中获得焦点,以转到当前选定的项目,而不是第一个 - Get the focus in a ButtonGroup of JRadioButtons to go to the currently selected item instead of first 如何使用WebDriver随机选择一个按钮? - How do I select a button randomly with WebDriver?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM