CheckboxGroup
Home Up Button Checkbox CheckboxGroup Choice Key List Menu Mouse Popup Window Text

 

A "CheckboxGroup" differs from a "Checkbox" in that only one item in the "CheckboxGroup" can be selected at a time.     Experiment with the applet below to see what it does.  Then proceed to understand the code that generates the applet.

An applet would appear here if your browser supported java.

To use a "CheckboxGroup", the "ItemListener" interface should be implemented.  This requires the "itemStateChanged" method to be implemented (see the event handling reference). 

The "init" method begins by setting the layout manger to be the null layout manager.  It then creates a "CheckboxGroup" named "colorGroup".  A "redCheckbox" is then created with the label "red" and as a member of the "colorGroup" component.  An item listener is added for the "redCheckbox", the "redCheckbox" is located and sized via the "setBounds" method, and then it is added to the display screen.  The final four lines of the "init" method go through exactly the same process with the "blueCheckbox".  Notice that since both the "redCheckbox" and the "blueCheckbox" are members of the "colorGroup" "CheckboxGroup" that only one of them can be active at a time.

The "itemStateChanged" method works by testing the label of the selected checkbox via the "getItem" method.  It sets the background color to match the label of the checkbox selected.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;          
public class Example extends Applet implements ItemListener
{
	public void init ()
	{
		setLayout(null);          
		CheckboxGroup colorGroup = new CheckboxGroup();          
		Checkbox redCheckbox = new Checkbox("red", colorGroup, false);
		redCheckbox.addItemListener(this);
		redCheckbox.setBounds(100,100,50,50);
		add(redCheckbox);	      
		Checkbox blueCheckbox = new Checkbox("blue", colorGroup, false);
		blueCheckbox.addItemListener(this);
		blueCheckbox.setBounds(150,100,50,50);
		add(blueCheckbox);
	}          
	public void itemStateChanged (ItemEvent evt)
	{          
		if (evt.getItem().equals("red"))
			setBackground (Color.red);
		else if (evt.getItem().equals("blue"))
			setBackground (Color.blue);    
		repaint();          
	}          
}