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 ?
I know should add an
actionlistenerto obtain the selected values , but what is the content I should code in theactionlistener?
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()
You have to call addActionListener() on the item you want to listen to, in this case it looks like you want to call it on your submit button. The action listener that you pass as a parameter then has the code that you want to execute. Check out the tutorial:
http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
For each form item you will have to look in the API to understand what method to call to get the correct value. For example: getText() or isSelected().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With