JCheckBox provides
the functionality of a checkbox. Its immediate superclass is JToggleButton, which provides the
support for two state button.
One commonly
used constructor for JCheckBox is:
JCheckBox(String
str)
It
creates a checkbox that has the text specified by str as a label.
When a user
selects or deselects a checkbox, an ItemEvent
is generated. We 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.
The easiest way
to determine the state of a checkbox is to call isSelected() on the JCheckBox
instance.
Example:
import
java.awt.*;
import
javax.swing.*;
import
java.awt.event.*;
public
class MyCheckBox extends JApplet implements ItemListener
{
JLabel l1;
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
} catch(Exception e){
System.out.println("Sorry some error
occured "+e);
}
}
private void makeGUI()
{
setLayout(new FlowLayout());
l1=new JLabel("Select Language");
JCheckBox cb=new JCheckBox ("C");
cb.addItemListener(this);
add(cb);
cb=new JCheckBox ("C++");
cb.addItemListener(this);
add(cb);
add(l1);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb=(JCheckBox)ie.getItem();
if(cb.isSelected())
l1.setText(cb.getText() + " is
selected");
else
l1.setText(cb.getText() + " is
deselected");
}
}
Output:
No comments:
Write comments