StackTest Applet



// testing the Stack class of the java.util package

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

public class StackTest extends Applet {

	Stack st;

	Label prompt;
	TextField input;
	Button pushBtn, popBtn, peekBtn, emptyBtn, searchBtn, displayBtn;
	
   public void init()
     	{
		st = new Stack();

		prompt = new Label( " Enter a string" );
		input = new TextField( 10 );
		pushBtn = new Button( "Push" );
		popBtn = new Button( "Pop" );
		peekBtn = new Button( "Peek" );
		emptyBtn = new Button( "Empty?");
		searchBtn = new Button( "Search");
		displayBtn = new Button( "Display");

		add( prompt );
		add( input );
		add( pushBtn );
		add( popBtn );
		add( peekBtn );
		add( emptyBtn );
		add( searchBtn );
		add( displayBtn );
	}

   public boolean action( Event e, Object o)
	{
		if ( e.target == pushBtn )
			showStatus( "Pushed: " + st.push( input.getText() ) ) ;
		else if ( e.target == popBtn ) {
			try {showStatus ( "Popped: " + st.pop() ); }
			catch (EmptyStackException ex)
			{ showStatus ( ex.toString() ); }
		}
		else if ( e.target == peekBtn ) {
			try {showStatus ( "Top: " + st.peek() ); }
			catch (EmptyStackException ex)
			{ showStatus ( ex.toString() ); }
		}
		else if ( e.target == emptyBtn ) {
			showStatus ( st.empty() ?  "Stack is empty " : "Stack is not empty");
		}
		else if ( e.target == searchBtn ) {
			String searchKey = input.getText();
			int result = st.search( searchKey );
			
			if (result == -1)
				showStatus (searchKey + " not found ");
			else
				showStatus (searchKey + " found at element " + result );
		}
		else if ( e.target == displayBtn ) {
			Enumeration enum = st.elements();
			StringBuffer buf = new StringBuffer();

			while ( enum.hasMoreElements() )
				buf.append ( enum.nextElement() ).append( " " );

			showStatus( buf.toString() );
		}
		
		return true;
	}
 }