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

 

A "Checkbox" is a box that a user can either check or uncheck by clicking on it.  Experiment with the applet below to see what it does.  Then proceed to understand the code that generates the applet.

A runnable applet would appear here if your browser supported Java.

The program implements the "ItemListener" interface, requiring that the "itemStateChanged" method be implemented (see the event handling reference).    The "init" method sets the layout manager to be the null layout manger.  It then creates a new "Checkbox" with the label "red".  Next, it adds an item listener for it so that the program can respond to the user clicking on the box.  Since the null layout manager is being used, the component must be given a location and size via the "setBounds" method.   Finally, the "redCheckbox" is added to the display window.The final four lines of code in the "init" method produce a "blueCheckbox" using exactly the same process as for the "redCheckbox".

The "itemStateChanged" method works as follows.  First, the "getState" method is invoked on each of the two "checkBox" components.   If both are selected, the background color is set to a purplish color (recall that purple is the addition of blue and red).  If just the "redCheckBox" is selected, the background color is set to red.  If just the "blueCheckBox" is selected, the background color is set to blue.  Otherwise the background color is set to gray.

 

import java.awt.*;
import java.awt.event.*;
import java.applet.*;                  
public class Example extends Applet implements ItemListener
{
	public void init ()
	{
		setLayout(null);                  
		redCheckbox = new Checkbox("red");
		redCheckbox.addItemListener(this);
		redCheckbox.setBounds(100,100,50,50);
		add(redCheckbox);		
		                  
		blueCheckbox = new Checkbox("blue");
		blueCheckbox.addItemListener(this);
		blueCheckbox.setBounds(150,100,50,50);
		add(blueCheckbox);
	}                  
	public void itemStateChanged (ItemEvent evt)
	{
		boolean red = redCheckbox.getState();
		boolean blue = blueCheckbox.getState();                  
		if (red && blue)
			setBackground (new Color(255,0,255);
		else if (red)
			setBackground (Color.red);
		else if (blue)
			setBackground (Color.blue);
		else
			setBackground (Color.gray);                  
		repaint();                  
	}                  
	private Checkbox redCheckbox;
	private Checkbox blueCheckbox;                  
}