Search code examples
javaswinguser-interfacejtextareajradiobutton

Displaying text from selected JRadioButton to JTextArea


I am working on my HOMEWORK (please don't do my work for me). I have 95% of it completed already. I am having trouble with this last bit though. I need to display the selected gender in the JTextArea. I must use the JRadioButton for gender selection.

I understand that JRadioButtons work different. I set up the action listener and the Mnemonic. I think I am messing up here. It would seem that I might need to use the entire group to set and action lister maybe.

Any help is greatly appreciated.

Here is what I have for my code (minus parts that I don't think are needed so others can't copy paste schoolwork):

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;


public class LuisRamosHW3 extends JFrame {

private JLabel WelcomeMessage;

private JRadioButton jrbMale = new JRadioButton("Male");

private JRadioButton jrbFemale = new JRadioButton("Female");

public LuisRamosHW3(){

setLayout(new FlowLayout(FlowLayout.LEFT, 20, 30));


JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(2,1));
jpRadioButtons.add(jrbMale);
jpRadioButtons.add(jrbFemale);
add(jpRadioButtons, BorderLayout.AFTER_LAST_LINE);


ButtonGroup gender = new ButtonGroup();
gender.add(jrbMale);
jrbMale.setMnemonic(KeyEvent.VK_B); 
jrbMale.setActionCommand("Male");
gender.add(jrbFemale);
jrbFemale.setMnemonic(KeyEvent.VK_B);
jrbFemale.setActionCommand("Female");

//Set defaulted selection to "male"
jrbMale.setSelected(true);

//Create Welcome button
JButton Welcome = new JButton("Submit");
add(Welcome);

Welcome.addActionListener(new SubmitListener());
WelcomeMessage = (new JLabel(" "));
add(WelcomeMessage);


}
class SubmitListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){

String FirstName = jtfFirstName.getText();
String FamName = jtfLastName.getText();
Object StateBirth = jcbStates.getSelectedItem();
String Gender = gender.getActionCommand(); /*I have tried different 
variations the best I do is get one selection to print to the text area*/

WelcomeMessage.setText("Welcome, " + FirstName + " " + FamName + " a "
+ gender.getActionCommmand + " born in " + StateBirth);
}
}
} /*Same thing with the printing, I have tried different combinations and just can't seem to figure it out*/ 

Solution

  • Suggestions:

    • Make your ButtonGroup variable, gender, a field (declared in the class) and don't declare it in the constructor which will limit its scope to the constructor only. It must be visible throughout the class.
    • Make sure that you give your JRadioButton's actionCommands. JRadioButtons are not like JButtons in that if you pass a String into their constructor, this does not automatically set the JRadioButton's text, so you will have to do this yourself in your code.
    • You must first get the selected ButtonModel from the ButtonGroup object via getSelection()
    • Then check that the selected model is not null before getting its actionCommand text.

    For example

    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    
    import javax.swing.*;
    
    public class RadioButtonEg extends JPanel {
       public static final String[] RADIO_TEXTS = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
    
       // *** again declare this in the class.
       private ButtonGroup buttonGroup = new ButtonGroup();
       private JTextField textfield = new JTextField(20);
    
       public RadioButtonEg() {
          textfield.setFocusable(false);
          JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
          for (String radioText : RADIO_TEXTS) {
             JRadioButton radioButton = new JRadioButton(radioText);
             radioButton.setActionCommand(radioText); // **** don't forget this
             buttonGroup.add(radioButton);
             radioButtonPanel.add(radioButton);
          }
    
          JPanel bottomPanel = new JPanel();
          bottomPanel.add(new JButton(new ButtonAction("Press Me", KeyEvent.VK_P)));
    
          setLayout(new BorderLayout());
          add(radioButtonPanel, BorderLayout.CENTER);
          add(bottomPanel, BorderLayout.PAGE_END);
          add(textfield, BorderLayout.PAGE_START);
       }
    
       private class ButtonAction extends AbstractAction {
          public ButtonAction(String name, int mnemonic) {
             super(name);
             putValue(MNEMONIC_KEY, mnemonic);
          }
    
          @Override
          public void actionPerformed(ActionEvent e) {
             ButtonModel model = buttonGroup.getSelection();
             if (model == null) {
                textfield.setText("No radio button has been selected");
             } else {
                textfield.setText("Selection: " + model.getActionCommand());
             }
    
          }
       }
    
       private static void createAndShowGui() {
          RadioButtonEg mainPanel = new RadioButtonEg();
    
          JFrame frame = new JFrame("RadioButtonEg");
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }