How to Create Radio Button in java

In this post, we will learn the use of the radio button and how to implement it in java. First, we need to import the Swing package in the program. One question is always coming in your mind what is Radio button so first we discuss what is the radio button. If we want to use the Radio button then we have to use class JRadioButton this class is mandatory for the radio button. If we want to select one option among multiple options then we will use this radio button. It is mostly used in exams and quiz competitions.

Learn: How to create checkbox in Java Swing

Constructors of Class JRadioButton

There are three constructors in the JRadioButton class. If we want to create a radio button with no text then we use JRadioButton(). If we want to use the radio button with some Text then we use JRadioButton(String s). If we want to use a radio button with a given text and some status then we use JRadioButton(String s, boolean b).

Implementation of Radio Button in Java Swing

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

class RadioTest implements ActionListener
{
JFrame fr;
JRadioButton cb1,cb2,cb3,cb4;
JTextArea ta;
ButtonGroup bg;
 RadioTest()
 {
 fr=new JFrame();
 fr.setLayout(null);
 fr.setSize(500,500);
 
 cb1=new JRadioButton("Burger");
 cb1.setBounds(50,50,100,30);
 fr.add(cb1);
 cb2=new JRadioButton("DOSA");
 cb2.setBounds(50,110,100,30);
 fr.add(cb2);
 cb3=new JRadioButton("Burger");
 cb3.setBounds(50,170,100,30);
 fr.add(cb3);
 cb4=new JRadioButton("Burger");
 cb4.setBounds(50,230,70,30);
 fr.add(cb4);
 bg=new ButtonGroup();
 bg.add(cb1);
 bg.add(cb2);
 bg.add(cb3);
 bg.add(cb4);
 cb1.addActionListener(this);
 cb2.addActionListener(this);
 cb3.addActionListener(this);
 cb4.addActionListener(this);
 ta=new JTextArea();
 ta.setBounds(200,50,200,200);
 fr.add(ta);
 fr.setVisible(true);
 }
 public static void main(String args[])
 {
 new RadioTest();
 }
 
 public void actionPerformed(ActionEvent e)
 {
 ta.setText("");
 if(cb1.isSelected())
 ta.setText("i like to eat"+cb1.getText());
 if(cb2.isSelected())
 ta.setText("i like to eat"+cb2.getText());
 if(cb3.isSelected())
 ta.setText("i like to eat"+cb3.getText());
 if(cb4.isSelected())
 ta.setText("i like to eat"+cb1.getText());
 }
 
 
 
 }
 
 
 
 
 
 
 
 

The output of the program

radio button in java swing

Output: radio button in java swing

 

Leave a Reply

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