How to create checkbox in Java Swing

In this program, we will learn how to create checkbox in java swing and how to implement it in java. first, we import the Java Swing package in this program. All subscribers want to ask one question and the question is what is a checkbox and what is the use of checkbox and how to implement it. Now we discuss the definition of checkbox If we want to select multiple options in given options in this situation we will use a checkbox.

You may also read,

Constructors of class JCheckBox

There are three constructors in the JCheckBox class. To create a checkbox with no text then we can use JCheckBox(). If we want to use checkbox with some Text then we will use JCheckBox(String s). If we want to use a checkbox with a given text and some status then we use JCheckBox(String s, boolean b).

Program of CheckBox in Java Swing

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

class CheckBox implements ActionListener
{
JFrame fr;
JCheckBox cb1,cb2,cb3,cb4;
JTextArea ta;
 CheckBox()
 {
 fr=new JFrame();
 fr.setLayout(null);
 fr.setSize(500,500);
 
 cb1=new JCheckBox("Burger");
 cb1.setBounds(50,50,100,30);
 fr.add(cb1);
 cb2=new JCheckBox("DOSA");
 cb2.setBounds(50,110,100,30);
 fr.add(cb2);
 cb3=new JCheckBox("Burger");
 cb3.setBounds(50,170,100,30);
 fr.add(cb3);
 cb4=new JCheckBox("Burger");
 cb4.setBounds(50,230,70,30);
 fr.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 CheckBox();
 }
 
 public void actionPerformed(ActionEvent e)
 {
 ta.setText("");
 if(cb1.isSelected())
 ta.setText(ta.getText()+"\n"+"i like to eat"+cb1.getText());
 if(cb2.isSelected())
 ta.setText(ta.getText()+"\n"+"i like to eat"+cb2.getText());
 if(cb3.isSelected())
 ta.setText(ta.getText()+"\n"+"i like to eat"+cb3.getText());
 if(cb4.isSelected())
 ta.setText(ta.getText()+"\n"+"i like to eat"+cb1.getText());
 }
 
 
 
 }
 

The output of the program

checkbox in java swing

Using the above code you can now easily create options with a checkbox. Hope you have enjoyed this tutorial.





Leave a Reply

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