Java Swing GUI

How to Get the State of JCheckBox in Java Swing

In this tutorial, we are going to see How to get the state of JCheckBox in Java Swing . JCheckBox is a Swing component that represents an element that shows a selected or unselected state. The user can change this state by clicking on the component’s checkbox.

A standard JCheckBox component contains a checkbox and a label that describes the purpose of the checkbox.

JCheckBox can generate an ActionListener interface. When we click on the checkbox, actionPerformed() method is called.
 


 

Java Program to Get the State of JCheckBox:

The following code shows how to get the state of a JCheckBox. The method to get the state is JCheckBox.isSelected() which returns a Boolean value.

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

public class StateOfCheckBox extends JFrame 
{
    public StateOfCheckBox() throws HeadlessException {
        initGUI();
    }

    private void initGUI() {
        setSize(200, 100);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // create a checkbox with a label
        JCheckBox cb = new JCheckBox("Test");
        cb.setSelected(true);

        cb.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae) { 
            // Get the state of the checkbox
            boolean state = cb.isSelected();
            if (state) {
               System.out.println("Check box is selected.");
            } else {
               System.out.println("Checkbox is not selected.");
            }
          }
        });
        //add the checkbox to the frame
        getContentPane().add(cb);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new StateOfCheckBox().setVisible(true);
            }
        });
    }
}

Output:


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 *