Java Swing How to - Get and Set the State of a JCheckbox Component, selected or not selected








Question

We would like to know how to get and Set the State of a JCheckbox Component, selected or not selected.

Answer

/*from  ww  w  .  j a  va 2s  . co m*/

import javax.swing.JCheckBox;

public class Main {
  public static void main(String[] argv) throws Exception {

    JCheckBox checkbox = new JCheckBox();

    // Get the current state of the checkbox
    boolean b = checkbox.isSelected();

    // Set the state of the checkbox to off
    checkbox.setSelected(false);

    // Set the state of the checkbox to on
    checkbox.setSelected(true);

  }
}