/* * File: CheckboxGroupTest.java * * Create some radio buttons, using Checkboxes with CheckboxGroup * and ItemEvents * * Copyright: Northeast Parallel Architectures Center * */ import java.awt.Color; import java.awt.Font; import java.awt.Label; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.Panel; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; public class CheckboxGroupTest extends java.applet.Applet implements ItemListener { private Label label; private int n = 6; // number of radio buttons private Checkbox[] radioButton = new Checkbox[n]; private CheckboxGroup radioButtons = new CheckboxGroup(); private Font f = new Font("Dialog", Font.PLAIN, 18); private Color purple = new Color (127, 0, 255); private String[] colorLabel = new String[n]; private Color[] colorlist = new Color[n]; public void init() { setBackground( Color.white ); setFont (f); colorLabel[0] = "Red"; colorLabel[1] = "Blue"; colorLabel[2] = "Yellow"; colorLabel[3] = "Green"; colorLabel[4] = "Magenta"; colorLabel[5] = "Purple"; colorlist[0] = Color.red; colorlist[1] = Color.blue; colorlist[2] = Color.yellow; colorlist[3] = Color.green; colorlist[4] = Color.magenta; colorlist[5] = purple; // Instantiate radio buttons and add them to the applet: for ( int i = 0; i < n; i++ ) { radioButton[i] = new Checkbox( colorLabel[i], radioButtons, false ); add( radioButton[i] ); // Register applet as an event listener with the radio button: radioButton[i].addItemListener( this ); } radioButtons.setSelectedCheckbox( radioButton[0] ); // Add label to the applet: label = new Label( " ", Label.LEFT ); add( label ); } public void itemStateChanged( ItemEvent event ) { updateLabel(); } public void updateLabel() { String str = " You chose color "; String cblabel = radioButtons.getSelectedCheckbox().getLabel() ; str += cblabel + "!"; for ( int i=0; i < n; i++) { if (cblabel.equals (colorLabel[i])) { label.setForeground ( colorlist[i]); break; } } label.setText(str); } }