Gets the value selected from the radio button in Java

import javax.swing.*;
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();
}
}

I know that an action listener should be added to get the selected value, but what should I write in the action listener?

Solution

In actionlistener, you can ask who is the source of action events, and then set the text of the text field as needed:

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

Note: it is recommended to read eventobject getSource()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>