3
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什么?

4

3 回答 3

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

于 2013-10-18T12:24:21.860 回答
3

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

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

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

于 2013-10-18T12:15:13.363 回答
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 ) );
于 2013-10-18T12:30:03.443 回答