4

我在一个 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

4 回答 4

6

从选定的 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 时才有效。例如,:

// 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]);
}
于 2012-04-08T22:33:03.040 回答
3

您看到的是该toString方法的默认实现。并将ButtonGroup#getSelection返回ButtonModel选定的JRadioButton.

另请参阅如何获取从 ButtonGroup 中选择的 JRadioButton

于 2012-04-08T22:31:30.493 回答
3

如果附加了侦听器,确定源的简单方法是调用ActionEvent.getSource().

于 2012-04-08T22:51:48.690 回答
1

这将从按钮组返回所选单选按钮的文本

    Enumeration<AbstractButton> allRadioButton=radioGroup.getElements();  
    while(allRadioButton.hasMoreElements())  
    {  
       JRadioButton temp=(JRadioButton)allRadioButton.nextElement();  
       if(temp.isSelected())  
       {  
          JOptionPane.showMessageDialog(null,"You select : "+temp.getText());  
       }  
    }            
于 2013-01-20T17:52:51.710 回答