Java: JCheckBox

Description

A javax.swing.JCheckBox shows a small box that is either marked or unmarked. When you click on it, it changes from checked to unchecked or vice versa automatically. You don't have to do any programming for the checkbox to change.

There are two ways to use a checkbox:

  1. Active. Use addActionListeneror addItemListener() so that a method will be called whenever the checkbox is changed.
  2. Passive. Use isSelected() to test if a checkbox is checked.

Common constructors and methods

Assume

   JCheckBox cb;     // A checkbox.
   String    text;   // Label on text box.
   boolean   state;  // True/false state of checkbox.
Constructors
cb = new JCheckBox(text); Creates check box, initially unchecked.
cb = new JCheckBox(text, state); Creates check box, checked or not depending on state.
Methods
state = cb.isSelected(); Returns true if the check box is checked.
 cb.setSelected(state); Checks (true) or unchecks check box.
 cb.addActionListener(action-listener); Adds an action listener to the radio button. The action listener will be called if button is selected.
 cb.addItemListener(item-listener); Add an item listener to a radio button. The item listener will be called if the button is selected or deselected.

Example using an ActionListener

An ActionListener should probably be preferred to an ItemListener, and this needs to have a little more explanation.

[EXAMPLE TO BE SUPPLIED]

Example with anonymous inner class ItemListener

This example creates a checkbox (ignoreCase) that is already checked, and adds it to the JPanel (content). It sets the boolean variable (ignore) whenever the box state is changed by the user.

boolean ignore = true;  // true if should ignore case
. . .
JCheckBox ignoreCase = new JCheckBox("Ignore Case", true);
ignoreCase.addItemListener(
    new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            // Set "ignore" whenever box is checked or unchecked.
            ignore = (e.getStateChange() == ItemEvent.SELECTED);
        }
    }
);
content.add(ignoreCase);

Example checking state

This example is similar to the above, but gets the state of the checkbox when the value is needed.
JCheckBox ignoreCase;
. . .
    //... inside window constructor
    JCheckBox ignoreCase = new JCheckBox("Ignore Case", true);
    content.add(ignoreCase);
    . . .
    
   //... Inside processing method, eg in button listener.
   if (ignoreCase.isSelected()) {
       . . .

Status: add sample image, mention icons, mention JCheckBoxMenuItem

Other