简体   繁体   English

如何从 ButtonGroup 中选择哪个 JRadioButton

[英]How do I get which JRadioButton is selected from a ButtonGroup

I have a swing application that includes radio buttons on a form.我有一个包含表单上的单选按钮的 Swing 应用程序。 I have the ButtonGroup , however, looking at the available methods, I can't seem to get the name of the selected JRadioButton .我有ButtonGroup ,但是,查看可用的方法,我似乎无法获得所选JRadioButton的名称。 Here's what I can tell so far:到目前为止,这是我能说的:

  • From ButtonGroup, I can perform a getSelection() to return the ButtonModel .从 ButtonGroup 中,我可以执行getSelection()来返回ButtonModel From there, I can perform a getActionCommand , but that doesn't seem to always work.从那里,我可以执行getActionCommand ,但这似乎并不总是有效。 I tried different tests and got unpredictable results.我尝试了不同的测试并得到了不可预测的结果。

  • Also from ButtonGroup , I can get an Enumeration from getElements() .同样从ButtonGroup ,我可以从getElements()获得一个枚举。 However, then I would have to loop through each button just to check and see if it is the one selected.但是,我将不得不遍历每个按钮以检查它是否是选定的按钮。

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 对此进行编程。

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.它返回所选按钮的文本。

I would just loop through your JRadioButtons and call isSelected() .我只是遍历您的JRadioButtons并调用isSelected() If you really want to go from the ButtonGroup you can only get to the models.如果您真的想从ButtonGroup转到模型,则只能访问模型。 You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?您可以将模型与按钮相匹配,但是如果您可以访问这些按钮,为什么不直接使用它们呢?

You must add setActionCommand to the JRadioButton then just do:您必须将setActionCommand添加到JRadioButton然后执行以下操作:

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());

I suggest going straight for the model approach in Swing.我建议直接采用 Swing 中的模型方法。 After you've put the component in the panel and layout manager, don't even bother keeping a specific reference to it.将组件放入面板和布局管理器后,甚至不必费心保留对它的特定引用。

If you really want the widget, then you can test each with isSelected , or maintain a Map<ButtonModel,JRadioButton> .如果你真的想要这个小部件,那么你可以用isSelected测试每个小部件,或者维护一个Map<ButtonModel,JRadioButton>

You can put and actionCommand to each radio button (string).您可以将 actionCommand 放入每个单选按钮(字符串)。

this.jButton1.setActionCommand("dog");
this.jButton2.setActionCommand("cat");
this.jButton3.setActionCommand("bird");

Assuming they're already in a ButtonGroup (state_group in this case) you can get the selected radio button like this:假设它们已经在 ButtonGroup(在这种情况下为 state_group)中,您可以像这样获得所选的单选按钮:

String selection = this.state_group.getSelection().getActionCommand();

Hope this helps希望这有帮助

The following code displays which JRadiobutton is selected from Buttongroup on click of a button.以下代码显示单击按钮时从 Buttongroup 中选择了哪个 JRadiobutton
It is done by looping through all JRadioButtons in a particular buttonGroup.它是通过循环遍历特定 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());  
           }  
        }            
     }
  }

Typically, some object associated with the selected radio button is required.通常,需要一些与所选单选按钮相关联的对象。 It is not necessarily a String representing the button's label.它不一定是表示按钮标签的String It could be an Integer containing the button's index or an object of more complicated type T .它可以是包含按钮索引的Integer或更复杂的类型T的对象。 You could fill and use a Map<ButtonModel, T> as Tom Hawtin suggested, but I propose to extend the model and place the objects there.您可以按照Tom Hawtin 的建议填充和使用Map<ButtonModel, T> ,但我建议扩展模型并将对象放置在那里。 Here's an improved ButtonGroup that uses this approach.这是使用这种方法的改进的ButtonGroup

import javax.swing.*;

@SuppressWarnings("serial")
public class SmartButtonGroup<T> extends ButtonGroup {
    @Override
    public void add(AbstractButton b) {
        throw new UnsupportedOperationException("No object supplied");
    }

    public void add(JRadioButton button, T attachedObject) {
        ExtendedModel<T> model = new ExtendedModel<>(attachedObject);
        model.setSelected(button.isSelected());
        button.setModel(model);
        super.add(button);
    }

    @SuppressWarnings("unchecked")
    public T getSelectedObject() {
        ButtonModel selModel = getSelection();
        return selModel != null ? ((ExtendedModel<T>)selModel).obj : null;
    }

    public static class ExtendedModel<T> extends javax.swing.JToggleButton.ToggleButtonModel {
        public T obj;

        private ExtendedModel(T object) {
            obj = object;
        }
    }
}

You can use this utility class instead of ButtonGroup .您可以使用此实用程序类代替ButtonGroup Create an object of this class and add buttons along with associated objects to it.创建此类的对象并向其添加按钮和关联对象。 For example,例如,

SmartButtonGroup<Integer> group = new SmartButtonGroup<>();
JPanel panel = new JPanel();

for (int i = 1; i <= 5; i++) {
    JRadioButton button = new JRadioButton("Button #" + i, i == 3); // select the 3rd button
    group.add(button, i);
    panel.add(button);
}

After this, you can get the object associated with the currently selected button anytime you need by simply calling getSelectedObject() , like this:在此之后,您可以随时通过简单地调用getSelectedObject()来获取与当前所选按钮关联的对象,如下所示:

int selectedButtonIndex = group.getSelectedObject();

In case you need just the buttons themselves, you can use the next non-generic class instead.如果您只需要按钮本身,则可以改用下一个非泛型类。

import javax.swing.JRadioButton;

@SuppressWarnings("serial")
public class RadioButtonGroup extends SmartButtonGroup<JRadioButton> {
    public void add(JRadioButton button) {
        super.add(button, button);
    }

    @Override
    public void add(JRadioButton button, JRadioButton attachedObject) {
        throw new UnsupportedOperationException("Use the short form of addition instead");
    }

    public JRadioButton getSelectedButton() {
        return getSelectedObject();
    }
}

You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items.您可以使用 ItemSelectable(ButtonModel 的超级接口)的 getSelectedObjects() 返回所选项目的列表。 In case of a radio button group it can only be one or none at all.如果是单选按钮组,它只能是一个或根本没有。

Add the radiobuttons to a button group then:将单选按钮添加到按钮组,然后:

buttonGroup.getSelection().getActionCommand buttonGroup.getSelection().getActionCommand

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());
    }
}

Use the isSelected() method.使用isSelected()方法。 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.将它与循环(例如 for 循环)结合使用,您可以找到已选择的那个。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 
public class MyJRadioButton extends JFrame implements ActionListener
{
    JRadioButton rb1,rb2;  //components
    ButtonGroup bg;
    MyJRadioButton()
{
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    rb1=new JRadioButton("male");
    rb2=new JRadioButton("female");

    //add radio button to button group
    bg=new ButtonGroup();
    bg.add(rb1);
    bg.add(rb2);

    //add radio buttons to frame,not button group
    add(rb1);
    add(rb2);
    //add action listener to JRadioButton, not ButtonGroup
    rb1.addActionListener(this);
    rb2.addActionListener(this);
    pack();
    setVisible(true);
}
public static void main(String[] args)
{
    new MyJRadioButton(); //calling constructor
}
@Override
public void actionPerformed(ActionEvent e) 
{
    System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}

} }

Ale Rojas's answer works fine: Ale Rojas 的回答很有效:

As alternative you can also use the My_JRadiobutton11.addActionListener(this);作为替代方案,您也可以使用My_JRadiobutton11.addActionListener(this); on your JButton and then make your actions in the actionPerformed function like this (It just uses an extra variable which you have to instantiate (eg Private String selection;) but it's not a big deal):在你的 JButton 上,然后像这样在 actionPerformed 函数中执行你的操作(它只使用一个你必须实例化的额外变量(例如私有字符串选择;)但这没什么大不了的):

public void actionPerformed(ActionEvent arg0) {
      if(arg0.getSource() == My_JRadiobutton11){
          //my selection
          selection = "Become a dolphin";
      }else if(arg0.getSource() == My_JRadiobutton12){
          //my selection
          selection = "Become a Unicorn";
      } ..etc 
 }
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());
    }

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

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