Java 如何从 ButtonGroup 中选择哪个 JRadioButton

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/201287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:17:01  来源:igfitidea点击:

How do I get which JRadioButton is selected from a ButtonGroup

javaswing

提问by Joel

I have a swing application that includes radio buttons on a form. I have the ButtonGroup, however, looking at the available methods, I can't seem to get the name of the selected JRadioButton. Here's what I can tell so far:

我有一个包含表单上的单选按钮的 Swing 应用程序。我有ButtonGroup,但是,查看可用的方法,我似乎无法获得所选JRadioButton. 到目前为止,这是我能说的:

  • From ButtonGroup, I can perform a getSelection()to return the ButtonModel. From there, I can perform a getActionCommand, but that doesn't seem to always work. I tried different tests and got unpredictable results.

  • Also from ButtonGroup, I can get an Enumeration from getElements(). However, then I would have to loop through each button just to check and see if it is the one selected.

  • 从 ButtonGroup 中,我可以执行 agetSelection()来返回ButtonModel. 从那里,我可以执行 a getActionCommand,但这似乎并不总是有效。我尝试了不同的测试并得到了不可预测的结果。

  • 同样从ButtonGroup,我可以从getElements(). 但是,我将不得不遍历每个按钮以检查它是否是选定的按钮。

Is there an easier way to find out which button has been selected? I'm programing this in Java 1.3.1 and Swing.

有没有更简单的方法来找出选择了哪个按钮?我正在用 Java 1.3.1 和 Swing 对此进行编程。

采纳答案by Draemon

I would just loop through your JRadioButtonsand call isSelected(). If you really want to go from the ButtonGroupyou can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?

我只会遍历您的JRadioButtons并调用isSelected(). 如果你真的想从ButtonGroup你只能得到模型。您可以将模型与按钮相匹配,但是如果您可以访问这些按钮,为什么不直接使用它们呢?

回答by Daniel Rikowski

You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.

您可以使用 ItemSelectable(ButtonModel 的超级接口)的 getSelectedObjects() 返回所选项目的列表。如果是单选按钮组,它只能是一个或根本没有。

回答by Chobicus

jRadioOne = new javax.swing.JRadioButton();
jRadioTwo = new javax.swing.JRadioButton();
jRadioThree = new javax.swing.JRadioButton();

... then for every button:

...然后对于每个按钮:

buttonGroup1.add(jRadioOne);
jRadioOne.setText("One");
jRadioOne.setActionCommand(ONE);
jRadioOne.addActionListener(radioButtonActionListener);

...listener

...听众

ActionListener radioButtonActionListener = new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioButtonActionPerformed(evt);
            }
        };

...do whatever you need as response to event

...做任何你需要的事情来响应事件

protected void radioButtonActionPerformed(ActionEvent evt) {            
       System.out.println(evt.getActionCommand());
    }

回答by Tom Hawtin - tackline

I suggest going straight for the model approach in Swing. After you've put the component in the panel and layout manager, don't even bother keeping a specific reference to it.

我建议直接采用 Swing 中的模型方法。将组件放入面板和布局管理器后,甚至不必费心保留对它的特定引用。

If you really want the widget, then you can test each with isSelected, or maintain a Map<ButtonModel,JRadioButton>.

如果你真的想要这个小部件,那么你可以用 测试每个小部件isSelected,或者维护一个Map<ButtonModel,JRadioButton>.

回答by Rendicahya

I got similar problem and solved with this:

我遇到了类似的问题并解决了这个问题:

import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;

public class GroupButtonUtils {

    public String getSelectedButtonText(ButtonGroup buttonGroup) {
        for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
            AbstractButton button = buttons.nextElement();

            if (button.isSelected()) {
                return button.getText();
            }
        }

        return null;
    }
}

It returns the text of the selected button.

它返回所选按钮的文本。

回答by Akki

The following code displays which JRadiobutton is selected from Buttongroupon click of a button.
It is done by looping through all JRadioButtons in a particular buttonGroup.

以下代码显示单击按钮时从 Buttongroup 中选择了哪个 JRadiobutton
它是通过循环遍历特定 buttonGroup 中的所有 JRadioButton 来完成的。

 JRadioButton firstRadioButton=new JRadioButton("Female",true);  
 JRadioButton secondRadioButton=new JRadioButton("Male");  

 //Create a radio button group using ButtonGroup  
 ButtonGroup btngroup=new ButtonGroup();  

 btngroup.add(firstRadioButton);  
 btngroup.add(secondRadioButton);  

 //Create a button with text ( What i select )  
 JButton button=new JButton("What i select");  

 //Add action listener to created button  
 button.addActionListener(this);  

 //Get selected JRadioButton from ButtonGroup  
  public void actionPerformed(ActionEvent event)  
  {  
     if(event.getSource()==button)  
     {  
        Enumeration<AbstractButton> allRadioButton=btngroup.getElements();  
        while(allRadioButton.hasMoreElements())  
        {  
           JRadioButton temp=(JRadioButton)allRadioButton.nextElement();  
           if(temp.isSelected())  
           {  
            JOptionPane.showMessageDialog(null,"You select : "+temp.getText());  
           }  
        }            
     }
  }

回答by Spoonaroony

Add the radiobuttons to a button group then:

将单选按钮添加到按钮组,然后:

buttonGroup.getSelection().getActionCommand

buttonGroup.getSelection().getActionCommand

回答by Backabock

import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;

public class RadioButton extends JRadioButton {

    public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
        public Object[] getSelectedObjects() {
            if ( isSelected() ) {
                return new Object[] { RadioButton.this };
            } else {
                return new Object[0];
            }
        }

        public RadioButton getButton() { return RadioButton.this; }
    }

    public RadioButton() { super(); setModel(new RadioButtonModel()); }
    public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }

    public static void main(String[] args) {
        RadioButton b1 = new RadioButton("A");
        RadioButton b2 = new RadioButton("B");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        b2.setSelected(true);
        RadioButtonModel model = (RadioButtonModel)group.getSelection();
        System.out.println(model.getButton().getText());
    }
}

回答by CoderBrain

Use the isSelected()method. It will tell you the state of your radioButton. Using it in combination with a loop(say for loop) you can find which one has been selected.

使用isSelected()方法。它会告诉您单选按钮的状态。将它与循环(例如 for 循环)结合使用,您可以找到已选择的那个。

回答by Majdi

You must add setActionCommandto the JRadioButtonthen just do:

您必须添加setActionCommandJRadioButton然后执行以下操作:

String entree = entreeGroup.getSelection().getActionCommand();

Example:

例子:

java = new JRadioButton("Java");
java.setActionCommand("Java");
c = new JRadioButton("C/C++");
c.setActionCommand("c");
System.out.println("Selected Radio Button: " + 
                    buttonGroup.getSelection().getActionCommand());