/* * File: CheckboxTest.java * * Demonstrate the use of Checkboxes and ItemEvents * Also the use of String methods toLowerCase, lastIndexOf and substring * * Copyright: Northeast Parallel Architectures Center * */ import java.awt.Color; import java.awt.Font; import java.awt.Label; import java.awt.Checkbox; import java.awt.Panel; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; public class CheckboxTest extends java.applet.Applet implements ItemListener { private Label label; private Checkbox[] box = new Checkbox[5]; private Font f = new Font("Dialog", Font.PLAIN, 18); public void init() { setBackground( Color.white ); setFont (f); Color lightBlue = new Color( 0xB0, 0xE0, 0xE6 ); Color navyBlue = new Color( 0x19, 0x19, 0x70 ); // Instantiate some checkboxes box[0] = new Checkbox( "Shoes" ); box[1] = new Checkbox( "Socks" ); box[2] = new Checkbox( "Pants" ); box[3] = new Checkbox( "Shirt" ); // Check the next box by default: boolean checked = true; box[4] = new Checkbox( "Underwear", checked ); // set properties of the checkboxes and add to the applet for ( int i = 0; i < box.length; i++ ) { box[i].setForeground( navyBlue ); box[i].setBackground( lightBlue ); box[i].setFont (f); add ( box[i] ); box[i].addItemListener( this ); } // Add label to the applet and update it: label = new Label( " ", Label.LEFT ); add( label ); updateLabel(); } public void itemStateChanged( ItemEvent event ) { // whenever any checkbox is checked, we look at all the checkboxes // and update the label updateLabel(); } public void updateLabel() { // Build string of comma-separated items: String str = ""; for ( int i = 0; i < 5; i++ ) { if ( box[i].getState() ) { if ( str.equals( "" ) ) str += " Don't forget your "; else str += ", "; str += box[i].getLabel().toLowerCase(); } } // Insert "and" in the appropriate place: if ( !str.equals( "" ) ) { str += "!"; int pos = str.lastIndexOf( "," ); if ( pos != -1 ) str = str.substring( 0, pos ) + " and" + str.substring( pos + 1 ); } // for the first time, make sure the string is long enough for FlowLayout // to give it a nice long size str += " "; label.setText( str ); // update label } }