Java Swing How to - Get or set the selection state of JCheckBox








Question

We would like to know how to get or set the selection state of JCheckBox.

Answer

/*from w  w w  .j  av  a 2  s.c om*/
import java.awt.FlowLayout;

import javax.swing.JCheckBox;
import javax.swing.JFrame;

public class Main extends JFrame {
  public Main() {
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.LEFT));

    JCheckBox checkBox = new JCheckBox("Check me!");
    checkBox.setSelected(true);

    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) {
    new Main().setVisible(true);
  }
}