1  /*
  2   *  File:  CheckboxGroupTest.java
  3   *
  4   *  Create some radio buttons, using Checkboxes with CheckboxGroup
  5   *       and ItemEvents
  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.CheckboxGroup;
 16  import java.awt.Panel;
 17  import java.awt.event.ItemListener;
 18  import java.awt.event.ItemEvent;
 19  
 20  public class CheckboxGroupTest extends java.applet.Applet
 21                                 implements ItemListener {
 22  
 23    private Label label;
 24    private int n = 6;  // number of radio buttons
 25    private Checkbox[] radioButton = new Checkbox[n];
 26    private CheckboxGroup radioButtons = new CheckboxGroup();
 27    private Font f = new Font("Dialog", Font.PLAIN, 18);
 28    private Color purple = new Color (127, 0, 255);
 29    private String[] colorLabel = new String[n];
 30    private Color[] colorlist = new Color[n];
 31    
 32    public void init() {
 33      setBackground( Color.white );
 34      setFont (f);
 35  
 36      colorLabel[0] = "Red";    colorLabel[1] = "Blue";
 37      colorLabel[2] = "Yellow"; colorLabel[3] = "Green";
 38      colorLabel[4] = "Magenta"; colorLabel[5] = "Purple";
 39  
 40      colorlist[0] = Color.red;    colorlist[1] = Color.blue;
 41      colorlist[2] = Color.yellow; colorlist[3] = Color.green;
 42      colorlist[4] = Color.magenta; colorlist[5] = purple;
 43      
 44      // Instantiate radio buttons and add them to the applet:
 45      for ( int i = 0; i < n; i++ ) {
 46        radioButton[i] = new Checkbox( colorLabel[i], radioButtons, false );
 47        add( radioButton[i] );
 48        // Register applet as an event listener with the radio button:
 49        radioButton[i].addItemListener( this );
 50      }
 51      radioButtons.setSelectedCheckbox( radioButton[0] );
 52      
 53      // Add label to the applet:
 54      label = new Label( "                                      ", Label.LEFT );
 55      add( label );
 56    }
 57  
 58    public void itemStateChanged( ItemEvent event ) {
 59      updateLabel();
 60    }
 61    
 62    public void updateLabel() {
 63      String str = "   You chose color ";
 64      String cblabel = radioButtons.getSelectedCheckbox().getLabel() ;
 65      str += cblabel + "!";
 66      for ( int i=0; i < n; i++)
 67        { 
 68          if (cblabel.equals (colorLabel[i]))
 69  	    { label.setForeground ( colorlist[i]); break; }
 70        }
 71      label.setText(str);
 72    }
 73    
 74  }