JCheckBox in java

 In Swing, a check box is a graphical user interface component that allows the user to select one or more options from a set of options. A check box displays a label and a box that can be checked or unchecked.

To create a check box in Swing, you can use the JCheckBox class. Here's an example code snippet that creates a check box:

java
JCheckBox checkBox = new JCheckBox("Option 1");

In this example, "Option 1" is the label for the check box. You can customize the label by passing a different string to the JCheckBox constructor.

To handle events when the user checks or unchecks the check box, you can add an ItemListener to the check box. Here's an example code snippet that demonstrates this:

java

JCheckBox checkBox = new JCheckBox("Option 1"); checkBox.addItemListener(new ItemListener() 

@Override
public void itemStateChanged(ItemEvent e) 

if (e.getStateChange() == ItemEvent.SELECTED) 
{
// The check box was selected System.out.println("Option 1 was selected"); 
 } 
else 

// The check box was deselected System.out.println("Option 1 was deselected"); 
 } 
 }
 }
);

In this example, an anonymous inner class is used to implement the ItemListener interface. The itemStateChanged() method is called when the state of the check box changes. The getStateChange() method returns the current state of the check box, and you can use this to perform different actions depending on whether the check box was selected or deselected.

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java