我想在这个面板初始化时选择随机单选按钮,但我不确定如何/如果我能做到这一点。
有没有办法从组中获取随机按钮并选择它?
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);
}
}
}
答案 0 :(得分:2)
你可以做的是保留你创建的所有单选按钮的列表/数组,然后使用按钮组的setSelected()方法设置所选择的按钮,如下所示
buttonGroup.setSelected(buttonsArray[randomButtonNum].getModel(), true);
答案 1 :(得分:1)
尝试使用Random
类。
// Library location
import java.util.Random;
//Inside some method
Random r = new Random();
randomIndex = r.nextInt(buttonText.length());
text = buttonText[randomIndex];
这需要安排适合您的实施,所显示的是“操作方法”和#39;的使用。
注意:
nextInt(args)
的参数是独占的。即将返回0 <= x < args
答案 2 :(得分:0)
我相信你正在寻找类似下面的解决方案。
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);;
}
}
答案 3 :(得分:0)
我创建了一个小方法,允许我设置任何单选按钮组。如果您不想使用if用于任何单选按钮,则非常方便。
public void setButtonGroup(int rdValue, Enumeration elements ){
while (elements.hasMoreElements()){
AbstractButton button = (AbstractButton)elements.nextElement();
if(Integer.parseInt(button.getActionCommand())==rdValue){
button.setSelected(true);
}
}
}
然后
setButtonGroup(randomIndex, yourButtonGroup.getElements());