Luis Ramos
Luis Ramos

Reputation: 529

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*/ 

Upvotes: 0

Views: 4013

Answers (2)

Amarnath
Amarnath

Reputation: 8855

I have done a similar kind of a problem on JTable where we get the selection from the radio group and then act accordingly. Thought of sharing the solution.

Here, I have grouped the radio buttons using the action listener and each radio button will have an action command associated with it. When the user clicks on a radio button then an action will be fired subsequently an event is generated where we deselect other radio button selection and refresh the text area with the new selection.

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;

public class RadioBtnToTextArea {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new RadioBtnToTextArea().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();

        JPanel panel = new JPanel(new BorderLayout());
        JPanel radioPnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JPanel textPnl = new JPanel();


        JRadioButton radioMale = new JRadioButton();
        JRadioButton radioFemale = new JRadioButton();

        JTextArea textArea = new JTextArea(10, 30);

        ActionListener listener = new RadioBtnAction(radioMale, radioFemale, textArea);

        radioPnl.add(new JLabel("Male"));
        radioPnl.add(radioMale);
        radioMale.addActionListener(listener);
        radioMale.setActionCommand("1");

        radioPnl.add(new JLabel("Female"));
        radioPnl.add(radioFemale);
        radioFemale.addActionListener(listener);
        radioFemale.setActionCommand("2");

        textPnl.add(textArea);

        panel.add(radioPnl, BorderLayout.NORTH);
        panel.add(textPnl, BorderLayout.CENTER);


        frame.add(panel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


class RadioBtnAction implements ActionListener {

    JRadioButton maleBtn;
    JRadioButton femaleBtn;
    JTextArea textArea;

    public RadioBtnAction(JRadioButton maleBtn, 
                                JRadioButton femaleBtn, 
                                    JTextArea textArea) {
        this.maleBtn = maleBtn;
        this.femaleBtn = femaleBtn;
        this.textArea = textArea;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        int actionCode = Integer.parseInt(e.getActionCommand());

        switch (actionCode) {
        case 1:
            maleBtn.setSelected(true);
            femaleBtn.setSelected(false);
            textArea.setText("Male");
            break;
        case 2: 
            maleBtn.setSelected(false);
            femaleBtn.setSelected(true);
            textArea.setText("Female");

            break;
        default:
            break;
        }   
    }

}

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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

Upvotes: 2

Related Questions