选择了哪个JRadioButton

时间:2012-04-08 22:25:11

标签: java swing jradiobutton buttongroup

我在ButtonGroup中有几个JRadioButtons。

   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.println(radioGroup.getSelection())我只能得到类似javax.swing.JToggleButton$ToggleButtonModel@32b3714的内容。

4 个答案:

答案 0 :(得分:6)

从选定的ButtonModel中,您可以获取actionCommand String(如果您记得设置它!)。

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

答案 1 :(得分:3)

您所看到的是toString方法的默认实现。 ButtonGroup#getSelection将返回所选ButtonModel的{​​{1}}。

另见How do I get which JRadioButton is selected from a ButtonGroup

答案 2 :(得分:3)

如果附加了听众,则确定来源的简便方法是致电ActionEvent.getSource()

答案 3 :(得分:1)

这将从buttongroup

返回所选单选按钮的文本
    Enumeration<AbstractButton> allRadioButton=radioGroup.getElements();  
    while(allRadioButton.hasMoreElements())  
    {  
       JRadioButton temp=(JRadioButton)allRadioButton.nextElement();  
       if(temp.isSelected())  
       {  
          JOptionPane.showMessageDialog(null,"You select : "+temp.getText());  
       }  
    }