// ComboBoxListDemo.java
// Examples of combo boxes and lists
// APPLET CODE="ComboBoxListDemo" HEIGHT=400 WIDTH=600
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ComboBoxListDemo extends JApplet implements ActionListener, ItemListener {
	Container c;
	JComboBox studClass;
	String years[ ] = { "Freshman", "Sophomore", "Junior", "Senior", "Graduate", "Auditor" };
	JCheckBox acct151, fin125, csc11, engl1;
	JTextField desc;
	JButton go, erase;

	String year;
	String bio = "";  // need to initialize to avoid nullPointerException
	String courses [ ];
	int k = -1;  // counter for klass

	public void init( ) {
		// build GUI
		c = getContentPane( );
		c.setLayout( new FlowLayout( ) );
		courses = new String[ 4 ];
		
		studClass = new JComboBox( years );
		studClass.setMaximumRowCount( 2 );
		studClass.addItemListener( this );
		c.add( studClass );

		acct151 = new JCheckBox( "Acct 151" );
		acct151.addItemListener( this );
		c.add( acct151 );
		fin125 = new JCheckBox( "Fin 125" );
		fin125.addItemListener( this );
		c.add( fin125 );
		csc11 = new JCheckBox( "CSc 11" );
		csc11.addItemListener( this );
		c.add( csc11 );
		engl1 = new JCheckBox( "Engl 1" );
		engl1.addItemListener( this );
		c.add( engl1 );

		desc = new JTextField( 50 );
		c.add( desc );

		go = new JButton( "Enter" );
		go.addActionListener( this );
		c.add( go );
		erase = new JButton( "Clear" );
		erase.addActionListener( this );
		c.add( erase );
	}

	// method called if a check box or radio button is changed
	public void itemStateChanged( ItemEvent e ) {
		if ( e.getSource( ) == acct151 )
			if ( e.getStateChange( ) == ItemEvent.SELECTED ) 
				courses[ ++ k ] = "Fin Acct";
		if ( e.getSource( ) == fin125 )
			if ( e.getStateChange( ) == ItemEvent.SELECTED ) 
				courses[ ++ k ] = "Bus Fin";
		if ( e.getSource( ) == csc11 )
			if ( e.getStateChange( ) == ItemEvent.SELECTED ) 
				courses[ ++ k ] = "Intro Comp";
		if ( e.getSource( ) == engl1 )
			if ( e.getStateChange( ) == ItemEvent.SELECTED ) 
				courses[ ++ k ] = "Lit";

		if ( e.getSource( ) == studClass )
			year = years[ studClass.getSelectedIndex( ) ];
	}
		
	// method called if either go or clear button is clicked
	public void actionPerformed( ActionEvent e ) {
		if ( e.getSource( ) == go ) {
			// build a concatenated string using the courses array
			for ( int i = 0; i <= k; i++ ) {
				bio = bio.concat( courses[ i ] );
				if ( i < k )
					bio = bio.concat( " and " );
			}
			desc.setText( "You are a " + year + " and have taken " + bio );
		} else {
			// reset the counter, the string, the check boxes and the course array
			k = -1;
			bio = "";
			acct151.setSelected( false );
			fin125.setSelected( false );
			csc11.setSelected( false );
			engl1.setSelected( false );
			for ( int i = 0; i < courses.length; i++ )
				courses[ i ] = "";
			desc.setText( "" );  // clear button erases text field
		}
	}
}