// Fig. 18.02: StackTest.java
// Testing the Stack class of the java.util package
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class StackTest extends Applet
              implements ActionListener {
   private Stack s;

   // GUI components
   private TextField input;
   private Button pushBtn, popBtn, peekBtn,
                  emptyBtn, searchBtn, displayBtn;

   public void init()
   {
      s = new Stack();

      add( new Label( "Enter a string" ) );
      input = new TextField( 10 );
      input.addActionListener( this );
      add( input );      // value to push or search for

      pushBtn = new Button( "Push" );
      pushBtn.addActionListener( this );
      add( pushBtn );    // push the input value

      popBtn = new Button( "Pop" );
      popBtn.addActionListener( this );
      add( popBtn );     // pop a value

      peekBtn = new Button( "Peek" );
      peekBtn.addActionListener( this );
      add( peekBtn );    // peek at the top 

      emptyBtn = new Button( "Is Empty?" );
      emptyBtn.addActionListener( this );
      add( emptyBtn );   // check if stack is empty

      searchBtn = new Button( "Search" );
      searchBtn.addActionListener( this );
      add( searchBtn );  // search for input value

      displayBtn = new Button( "Display" );
      displayBtn.addActionListener( this );
      add( displayBtn ); // display the stack contents
   }

   public void actionPerformed( ActionEvent e )
   {
      if ( e.getSource() == pushBtn ) 
         showStatus( "Pushed: " + s.push( input.getText() ) );
      else if ( e.getSource() == popBtn ) {
         try {
            showStatus( "Popped: " + s.pop() );
         }
         catch ( EmptyStackException exception ) {
            showStatus( exception.toString() );
         }
      }
      else if ( e.getSource() == peekBtn ) {
         try {
            showStatus( "Top: " + s.peek() );
         }
         catch ( EmptyStackException exception ) {
            showStatus( exception.toString() );
         }
      }
      else if ( e.getSource() == emptyBtn ) {
         showStatus( s.empty() ? "Stack is empty" :
                                 "Stack is not empty" );
      }
      else if ( e.getSource() == searchBtn ) {
         String searchKey = input.getText();
         int result = s.search( searchKey );

         if ( result == -1 ) 
            showStatus( searchKey + " not found" );
         else
            showStatus( searchKey + " found at element " +
                        result );
      }
      else if ( e.getSource() == displayBtn ) {
         Enumeration enum = s.elements();
         StringBuffer buf = new StringBuffer();
        
         while ( enum.hasMoreElements() )
            buf.append( enum.nextElement() ).append( " " );
       
         showStatus( buf.toString() );
      }
   }
}