/* * 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.*; import java.awt.event.*; import javax.swing.*; import java.net.*; public class CheckboxTest extends JApplet implements ItemListener { private JLabel label; private JCheckBox[] box = new JCheckBox[5]; private Font f = new Font("Dialog", Font.PLAIN, 18); private ImageIcon icon1,icon2; public void init() { try{ icon1=new ImageIcon(new URL("http://www.npac.syr.edu/projects/webtech/java/examples1.2/checkboxtest/bulb1.gif")); icon2=new ImageIcon(new URL("http://www.npac.syr.edu/projects/webtech/java/examples1.2/checkboxtest/bulb2.gif")); } catch (Exception e){} getContentPane().setLayout(new GridLayout(7,1)); getContentPane().setBackground( Color.white ); getContentPane().setFont (f); Color lightBlue = new Color( 0xB0, 0xE0, 0xE6 ); Color navyBlue = new Color( 0x19, 0x19, 0x70 ); // Instantiate some checkboxes box[0] = new JCheckBox( "Shoes" , icon1); box[1] = new JCheckBox( "Socks" , icon1); box[2] = new JCheckBox( "Pants" , icon1); box[3] = new JCheckBox( "Shirt" , icon1); // Check the next box by default: boolean checked = true; box[4] = new JCheckBox( "Underwear", icon2, 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); getContentPane().add ( box[i] ); box[i].addItemListener( this ); } // Add label to the applet and update it: label = new JLabel( " ", JLabel.LEFT ); getContentPane().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].getModel().isPressed() ) changeIcon(box[i]); if ( box[i].isSelected() ) { if ( str.equals( "" ) ) str += " Don't forget your "; else str += ", "; str += box[i].getLabel().toLowerCase(); } }//end for // 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 } public void changeIcon(JCheckBox c) { if (c.getIcon()==icon1) { c.setIcon(icon2); } else { c.setIcon(icon1); } } }//end class