Java 选择了哪个JRadioButton
我在一个按钮组中有几个JradioButtonJava 选择了哪个JRadioButton,java,swing,jradiobutton,buttongroup,Java,Swing,Jradiobutton,Buttongroup,我在一个按钮组中有几个JradioButton private ButtonGroup radioGroup= new ButtonGroup(); private JRadioButton radio1= new JRadioButton("Red"); private JRadioButton radio2= new JRadioButton("Green"); private JRadioButton radio3= new JRadioButton("Blue")
private ButtonGroup radioGroup= new ButtonGroup();
private JRadioButton radio1= new JRadioButton("Red");
private JRadioButton radio2= new JRadioButton("Green");
private JRadioButton radio3= new JRadioButton("Blue");
radioGroup.add(radio1);
radioGroup.add(radio2);
radioGroup.add(radio3);
如何检查选择了哪一个?
使用System.out.printlnradioGroup.getSelection,我只能得到类似javax.swing.JToggleButton的东西$ToggleButtonModel@32b3714.您看到的是toString方法的默认实现。ButtonGroupgetSelection将返回所选JRadioButton的ButtonModel
另请参见。如果记得设置actionCommand字符串,则可以从所选按钮模型中获取该字符串
// code not compiled, run, nor tested in any way
ButtonModel model = radioGroup.getSelection();
String actionCommand = (model == null) ? "" : model.getActionCommand():
System.out.println(actionCommand);
但这只有在您首先设置actionCommand时才起作用。e、 g.,:
// code not compiled, run, nor tested in any way
String[] colors = {"Red", "Green", "Blue"};
JRadioButton[] radioBtns = new JRadioButton[colors.length];
for (int i = 0; i < radioBtns.length; i++) {
radioBtns[i] = new JRadioButton(colors[i]);
radioBtns[i].setActionCommand(colors[i]);
radioGroup.add(radioBtns[i]);
somePanel.add(radioBtns[i]);
}
如果附加了侦听器,确定来源的简单方法是调用。这将从buttongroup返回所选radiobutton的文本
Enumeration<AbstractButton> allRadioButton=radioGroup.getElements();
while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
JOptionPane.showMessageDialog(null,"You select : "+temp.getText());
}
}
+1但是从Darryl的,编辑这个人真的是一个外星人,实现了自定义定稿,bump…@mKorbel我希望我看到更多或任何Darryl关于这些部分的事情。