Java JCheckBox

The JCheckBox class provides the functionality of a checkbox. Its immediate superclass is JToggleButton, which provides support for two-state buttons. JCheckBox defines several constructors:

JCheckBox(String str)

When the user selects or deselects a checkbox, an ItemEvent is generated. You can obtain a reference to the JCheckBox that generated the event by calling getItem() on the ItemEvent passed to the itemStateChanged() method defined by ItemListener. It is the easiest way to determine the selected state of a checkbox is to call isSelected() on the JCheckBox instance.
In addition to supporting the normal checkbox operation, JCheckBox lets you specify the icons that indicate when a checkbox is selected, cleared and rolled over.

Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CheckBox extends JApplet implements ItemListener
{
JLabel jlab;
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch (Exception exc)
{
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
setLayout(new FlowLayout());
JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);
jlab = new JLabel("Select languages");
add(jlab);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
}
}