How to disable JCheckBox if not checked in Java


The following is an example to disable JCheckBox if not checked in Java:

Example

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
public class SwingDemo {
   public static void main(String[] args) {
      JCheckBox checkBox = new JCheckBox("Demo", true);
      checkBox.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (checkBox.isEnabled())
               checkBox.setEnabled(false);
            else
               checkBox.setEnabled(true);
         }
      });
      JOptionPane.showMessageDialog(null, checkBox);
   }
}

Output

Now, when you will uncheck the above checkbox, it will get disabled:

Updated on: 30-Jul-2019

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements