Java Reference
In-Depth Information
CheckBoxesPanel to control the color of the top OutputPanel . The
CheckBoxesPanel holds three checkboxes, and implements the ItemLis-
tener interface. A reference to the CheckBoxesPanel instance is added to
the ItemListener list for the checkboxes.
JCheckBox inherits from the Swing AbstractButton class and one
ActionEven t and one ItemEvent are fired each time a checkbox is clicked
with the mouse button. You could listen for both event types but it only makes
sense to listen for one type or the other. In most applications, it makes more sense
to use an item listener because ItemEvents have the advantage of providing an
easy way to tell whether the event was a selection or de-selection event.
The ItemEvent objects are handled by the itemStateChanged() method
in the ItemListener interface. Our implementation of this method first looks
to see if the event is due to a selection or de-selection. Then it examines each
checkbox using the isSelected() method to determine if it is in a selected
state or not.
If a checkbox is selected, then the corresponding color component (red,
green, or blue) is added to the combined color for the background of the
OutputPanel using the setColor (int red, int green, int
blue) method. (See the Web Course demos for the non-gray scale versions!)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/** The CheckBoxesPanel holds the checkboxes that set
* the color of the output panel.
**/
public class CheckBoxesPanel extends JPanel
implements ItemListener
{
JCheckBox fRed, fGreen, fBlue;
OutputPanel fOutputPanel;
/** Constructor adds 3 checkboxes to the panel. **/
CheckBoxesPanel (OutputPanel output - panel) {
fOutputPanel = output - panel;
// Initial color is red so select this button.
fRed = new JCheckBox ( " Red " , true);
fRed.addItemListener (this);
add (fRed);
 
Search WWH ::




Custom Search