Java Swing How to - Disable JCheckBox if not checked








Question

We would like to know how to disable JCheckBox if not checked.

Answer

//  w w  w  . j ava 2s. co  m
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

public class Main {
  public static void main(String[] args) {
    JCheckBox checkBox = new JCheckBox("Enabled", true);

    checkBox.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {
        if (checkBox.isEnabled())
          checkBox.setEnabled(false);
        else
          checkBox.setEnabled(true);
      }
    });
    JOptionPane.showMessageDialog(null, checkBox);
  }
}