// URLSelectorTextField.java
// Desired URL is entered in a textfield
// Corrects for partially entered URLs
import java.awt.*;
import java.applet.Applet;
import java.net.*;

public class URLSelectorTextField extends Applet {
	// String variables to correct for partially entered URLs
	private String s;
	private String h;
	private String hw;
	private Label l;
	private TextField t;
	private Button b;

	private URL location;

	public void init( ) {
		h = "http://";
		hw = "http://www.";

		l = new Label( "Enter site's URL" );
		t = new TextField( "", 60 );
		b = new Button( "GO" );
		add( l );
		add( t );
		add( b );
	}

	public boolean action ( Event e, Object arg ) {
		if ( e.target instanceof Button || e.target instanceof TextField ) {
			
			s = t.getText( );
			if ( s.substring( 0, 3).equals( "www" ) )
				s = h.concat( s );  // add http://
			else if ( s.substring( 0, 4 ).equals( "http" ) )
				s = t.getText( );  // do nothing 
			else
				s = hw.concat( s );  // add http://www.

			try {
				location = new URL( s );  // create the URL location from entered string
			}
			catch ( MalformedURLException ex ) {
				System.err.println( "Invalid URL" );
			}			
			
			gotoSite( location );
			return true;  // event handled
		}

		return false;  // event not handled yet
	}

	public void gotoSite( URL loc ) {
		//  this must be executed in a browser
		getAppletContext( ).showDocument( loc );
	}
}