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.example.swing;

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

public class CheckBoxState extends JFrame {
    public CheckBoxState() throws HeadlessException {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

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

        //
        // 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.");
        }

        getContentPane().add(checkBox);
    }

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

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply