Java Swing GUI

How to get Value of Selected JRadioButton in Java

In this tutorial, we are going to see how to get the value of selected JRadioButton in Java. We use JRadioButton class to create a radio button. The radio button is used to select one of several options. It is used to fill in forms, online documents, and MCQs.

We add radio buttons to a group so that only one radio button can be selected at a time. We use “ButtonGroup” class to create a button group and add a radio button to a group.

JRadioButton can generate an ActionListener interface. When we click on the radio button, the actionPerformed() method is called.

Use ButtonGroup.getSelection().getActionCommand() to get the value selected by the user.
 


[st_adsense]  

Java Program to get Value of Selected JRadioButton:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class RadioButtonValue extends JFrame implements ActionListener 
{  
   private ButtonGroup group;

   private static void init() 
   {
      //create a frame
      JFrame frame = new RadioButtonValue();
 
      //make the frame visible
      frame.pack();
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
 
   public static void main(String[] args) {
      //create and display the graphical interface
      javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            init();
         }
      });
   }
   
   public RadioButtonValue() 
   {
      // define the flow layout for the frame
      this.getContentPane().setLayout(new FlowLayout());
 
      JRadioButton blue = new JRadioButton("Blue");
      blue.setActionCommand("Blue");
 
      JRadioButton red = new JRadioButton("Red");
      red.setActionCommand("Red");
 
      JRadioButton green = new JRadioButton("Green");
      green.setActionCommand("Green");
    
      blue.setSelected(true);
    
      JButton btn = new JButton("Click here");
      btn.addActionListener(this);
      group = new ButtonGroup();
 
      //add radio buttons
      group.add(blue);
      group.add(red);
      group.add(green);
 
      add(blue);
      add(red);
      add(green);
      add(btn);
   }
 
   @Override
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Click here")) {
         System.out.println("The selected radio button is: " + 
                  group.getSelection().getActionCommand());
      }
   }
}

Output:


[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *