How do I get or set the state of JCheckBox?

This simple example shows you how to get or set the state of a JCheckBox. The method to set the state is JCheckBox.setSelected(boolean) and the method for getting the state is JCheckBox.isSelected() which return a boolean value.

package org.kodejava.swing;

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

public class CheckBoxState extends JFrame {
    public CheckBoxState() throws HeadlessException {

    private void initialize() {
        setSize(500, 500);
        setTitle("JCheckBox Demo");
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Creating checkbox with text label
        JCheckBox checkBox = new JCheckBox("Check me!");

        // Get checkbox selection state
        boolean selected = checkBox.isSelected();
        if (selected) {
            System.out.println("Check box state is selected.");
        } else {
            System.out.println("Check box state is not selected.");


    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CheckBoxState().setVisible(true));

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.