
// Greetings.java
// Burton Rosenberg, 3 July 1997

/* An example Java Applet which demonstrates
   GridLayout, BorderLayouts, layout nesting,
   Labels, Checkboxes and TextFields.
*/


import java.awt.* ;
import java.applet.* ;

public class Greetings extends Applet {

    TextField textIn  = new TextField(40) ;
    TextField textOut = new TextField(40)  ;
    CheckboxGroup cbg = new CheckboxGroup() ;
    Checkbox [] cbArray = new Checkbox[3] ;
    String [] cbLabel = { "Hello", "Goodbye", "Nix" } ;
    String [] greetingText = { "Hi ", "Bye ", "You're Fired " } ;
    
    public void init() {
	
	setLayout( new BorderLayout() ) ;
	Panel relaxedPanel = new Panel() ;
	relaxedPanel.setLayout( new GridLayout(0,2) ) ;
	add("North", relaxedPanel ) ;

	for ( int i = 0; i<cbArray.length; i++ ) {
	    cbArray[i] = new Checkbox(cbLabel[i], cbg, i==0) ;
	    // System.out.println(cbArray[i]) ;
	    relaxedPanel.add(cbArray[i]) ;
	}
	// fill out to an even number of items
	if ( cbArray.length%2 == 1 ) relaxedPanel.add(new Label()) ;
	
	relaxedPanel.add(new Label("Enter your name:")) ;
	relaxedPanel.add(textIn) ;
	relaxedPanel.add(new Label("Your Greeting is:")) ;
	relaxedPanel.add(textOut) ;
	validate() ;
    }
    
    public boolean action( Event e, Object arg ) {
    // override to catch return key pressed in textField
    // and to catch the change-of-state on any checkbox.
	if ( e.target == textIn || checkBoxAction(e) ) {
	    // our event

	    // check of text in
	    if ( textIn.getText().length() == 0 ) {
		// person didn't input anything.
		textOut.setText("No name, no Greeting!") ;
		return true ;
	    }

	    int i ;
	    for ( i=0; i<cbArray.length; i++ ) {
		if (cbArray[i].getState() ) {
		    // this box is checked
		    textOut.setText( greetingText[i] + textIn.getText() ) ;
		    return true ;
		}
	    }
	}
	// else not our event
	return false ;
    }

    private boolean checkBoxAction(Event e) {
    // check if e is one of our checkboxes
	int i ;
	for ( i=0; i<cbArray.length; i++ )
	    if ( e.target==cbArray[i] ) return true ;
	return false ;
    }
}
