获取从java中的单选按钮中选择的值

时间:2013-10-18 12:11:15

标签: java swing jradiobutton

import javax.swing.*;

import java.awt.*;

public class RadioButtonTest extends JFrame {

private JTextField jtfAnswer = new JTextField(10);
private JRadioButton jrbMale = new JRadioButton("Male");
private JRadioButton jrbFemale = new JRadioButton("Female");
private JButton jbSubmit = new JButton("Submit");

public RadioButtonTest(){
    setLayout(new GridLayout(5,1));

    ButtonGroup group = new ButtonGroup();
    group.add(jrbMale);
    group.add(jrbFemale);

    add(new Label("Select gender:"));
    add(jrbMale);
    add(jrbFemale);
    add(jtfAnswer);
    add(jbSubmit);

    setTitle("Radio Button");
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocation(200, 200);
    setSize(150, 150);
    setVisible(true);
}

public static void main(String[] args) {
    new RadioButtonTest();
}
}

我知道应该添加actionlistener来获取所选的值,但我应该在actionlistener编码的内容是什么?

3 个答案:

答案 0 :(得分:4)

  

我知道应该添加actionlistener来获取所选的值,   但是我应该在actionlistener编码的内容是什么?

ActionListener内,您可以询问操作事件的来源是谁,然后根据需要设置文本字段的文本:

ActionListener actionListener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() instanceof JRadioButton){
            JRadioButton radioButton = (JRadioButton) e.getSource();
            if(radioButton.isSelected()){
                jtfAnswer.setText(radioButton.getText());
            }
        }
    }
};

jrbMale.addActionListener(actionListener);
jrbFemale.addActionListener(actionListener);

注意建议阅读EventObject.getSource()

答案 1 :(得分:3)

您必须在要收听的项目上调用addActionListener(),在这种情况下,您似乎想在提交按钮上调用它。作为参数传递的动作侦听器将具有您要执行的代码。看看教程:

http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

对于每个表单项,您必须查看API以了解要调用哪种方法来获取正确的值。例如:getText()isSelected()

答案 2 :(得分:0)

像这样创建自己的动作列表:

class CustomActionListener implements ActionListener{

    private JTextField textField;
    private JRadioButton btn;
    public CustomActionListener( JRadioButton btn, JTextField field){
        this.btn = btn;
        this.textField = field;
    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        this.textField.setText( this.btn.getText() );

    }

}

然后将其添加到您的单选按钮:

jrbMale.addActionListener( new CustomActionListener( jrbMale, jtfAnswer ) );
jrbFemale.addActionListener( new CustomActionListener( jrbFemale, jtfAnswer ) );