简体   繁体   English

选择了哪个 JRadioButton

[英]Which JRadioButton selected

I have several JRadioButtons in a ButtonGroup.我在 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");

   radioGroup.add(radio1);
   radioGroup.add(radio2);
   radioGroup.add(radio3);

How can I check which one was selected?如何查看选择了哪一个?

With System.out.println(radioGroup.getSelection()) I only get something like javax.swing.JToggleButton$ToggleButtonModel@32b3714 .使用System.out.println(radioGroup.getSelection())我只得到类似javax.swing.JToggleButton$ToggleButtonModel@32b3714的东西。

From the selected ButtonModel, you can get the actionCommand String (if you remember to set it.).从选定的 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);

But this will only work if you set the actionCommand first.但这只有在您首先设置 actionCommand 时才有效。 eg,:例如,:

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

What you're seeing is the default implementation of the toString method.您看到的是toString方法的默认实现。 And ButtonGroup#getSelection will return the ButtonModel of the selected JRadioButton . ButtonGroup#getSelection将返回所选JRadioButtonButtonModel

See also How do I get which JRadioButton is selected from a ButtonGroup .另请参阅如何获取从 ButtonGroup 中选择的 JRadioButton

If listeners are attached, an easy way to determine the source is to call ActionEvent.getSource() .如果附加了侦听器,确定来源的一种简单方法是调用ActionEvent.getSource()

This will return the text of selected radiobutton from buttongroup这将从按钮组返回所选单选按钮的文本

    Enumeration<AbstractButton> allRadioButton=radioGroup.getElements();  
    while(allRadioButton.hasMoreElements())  
    {  
       JRadioButton temp=(JRadioButton)allRadioButton.nextElement();  
       if(temp.isSelected())  
       {  
          JOptionPane.showMessageDialog(null,"You select : "+temp.getText());  
       }  
    }            

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM