Get value that been selected from radio button in java

Adriel picture Adriel · Oct 18, 2013 · Viewed 46.4k times · Source
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 should add an actionlistener to obtain the selected values , but what is the content I should code in the actionlistener ?

Answer

dic19 picture dic19 · Oct 18, 2013

I know should add an actionlistener to obtain the selected values , but what is the content I should code in the actionlistener?

Inside your ActionListener you can ask who's the source of the action event and then set the text field's text 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 suggested reading EventObject.getSource()