1  /*
  2   *  File:  CheckboxTest.java
  3   *
  4   *  Demonstrate the use of Checkboxes and ItemEvents
  5   *  Also the use of String methods toLowerCase, lastIndexOf and substring
  6   *
  7   *  Copyright:  Northeast Parallel Architectures Center
  8   *  
  9   */
 10  
 11  import java.awt.Color;
 12  import java.awt.Font;
 13  import java.awt.Label;
 14  import java.awt.Checkbox;
 15  import java.awt.Panel;
 16  import java.awt.event.ItemListener;
 17  import java.awt.event.ItemEvent;
 18  
 19  public class CheckboxTest extends java.applet.Applet
 20                            implements ItemListener {
 21  
 22    private Label label;
 23    private Checkbox[] box = new Checkbox[5];
 24    private Font f = new Font("Dialog", Font.PLAIN, 18);
 25  
 26    public void init() {
 27      setBackground( Color.white );
 28      setFont (f);
 29  
 30      Color lightBlue = new Color( 0xB0, 0xE0, 0xE6 );
 31      Color  navyBlue = new Color( 0x19, 0x19, 0x70 );
 32  
 33      // Instantiate some checkboxes
 34      box[0] = new Checkbox( "Shoes" );
 35      box[1] = new Checkbox( "Socks" );
 36      box[2] = new Checkbox( "Pants" );
 37      box[3] = new Checkbox( "Shirt" );
 38      // Check the next box by default:
 39      boolean checked = true;
 40      box[4] = new Checkbox( "Underwear", checked );
 41      
 42      // set properties of the checkboxes and add to the applet
 43      for ( int i = 0; i < box.length; i++ ) {
 44        box[i].setForeground(  navyBlue );
 45        box[i].setBackground( lightBlue );
 46        box[i].setFont (f);
 47        add ( box[i] );
 48        box[i].addItemListener( this );
 49      }
 50      
 51      // Add label to the applet and update it:
 52      label = new Label( " ", Label.LEFT );
 53      add( label ); updateLabel();
 54    }
 55  
 56    public void itemStateChanged( ItemEvent event ) {
 57    // whenever any checkbox is checked, we look at all the checkboxes
 58    //    and update the label
 59      updateLabel();
 60    }
 61      
 62    public void updateLabel() {
 63      // Build string of comma-separated items:
 64      String str = "";
 65      for ( int i = 0; i < 5; i++ ) {
 66        if ( box[i].getState() ) {
 67          if ( str.equals( "" ) )  str += "   Don't forget your ";
 68          else str += ", ";
 69          str += box[i].getLabel().toLowerCase();
 70        }
 71      }
 72      // Insert "and" in the appropriate place:
 73      if ( !str.equals( "" ) ) {
 74        str += "!";
 75        int pos = str.lastIndexOf( "," );
 76        if ( pos != -1 )
 77          str = str.substring( 0, pos ) + " and" + str.substring( pos + 1 );
 78      }
 79      // for the first time, make sure the string is long enough for FlowLayout
 80      //    to give it a nice long size
 81      str += "                                 ";
 82      label.setText( str );  // update label
 83    }
 84    
 85  }