Syntax error How to get or set the selection state of JCheckBox in Java

How to get or set the selection state of JCheckBox in Java



The following is an example to get or set the selection state of JCheckBox:

Example

import java.awt.FlowLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class SwingDemo extends JFrame {
   public SwingDemo() {
      setSize(500, 500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout(new FlowLayout(FlowLayout.CENTER));
      JCheckBox checkBox = new JCheckBox("Demo");
      checkBox.setSelected(true);
      boolean sel = checkBox.isSelected();
      if (sel)
         System.out.println("Check box selected!");
      getContentPane().add(checkBox);
   }
   public static void main(String[] args) {
      new SwingDemo().setVisible(true);
   }
}

Output

Since the checkbox is selected by default, the following output would be visible in EclipseIDE:

Updated on: 2019-07-30T22:30:26+05:30

359 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements