FileDocCategorySizeDatePackage
Browser1.javaAPI DocExample1841Mon Oct 16 19:44:08 BST 2000None

Browser1.java

// File: Browser1.java
// Tim Balls : Sept 1999
// A basic html browser.

// Displays the contents of a URL
// Can follow hyperlinks
// Uses Swing classes : JFrame and JEditorPane

// The import statements have been made specific to indicate
// the precise location of each class/interface.
// The more usual "import javax.swing.*;" is quite OK

import javax.swing.JFrame;
import javax.swing.JEditorPane;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import java.awt.event.*;

public class Browser1 extends JFrame implements HyperlinkListener
{	public static void main( String[] args )
	{	new Browser1( args[0] );
	}

	private JEditorPane html;
	private URL url;
	public Browser1( String site )
	{	setSize( 350, 450 );
		setTitle( "Basic Browser" );
		addWindowListener( new WindowAdapter() {
			public void windowClosing( WindowEvent e )
			{	System.exit( 0 );
			}
		});

		try
		{	url = new URL( site );
		}
		catch( MalformedURLException e )
		{	System.out.println( "Invalid URL specified" );
			System.exit( 0 );
		}
		try
		{	html = new JEditorPane( url );
		}
		catch( IOException e )
		{	System.out.println( "Can't load url: " + url );
			System.exit( 0 );
		}
		
		getContentPane().add( html );
		html.setEditable( false ); // to allow links to be activated
		html.addHyperlinkListener( this );

		setVisible( true );
	}

	// When a hyperlink is "clicked" :-
	public void hyperlinkUpdate( HyperlinkEvent e )
	{	if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
		{	try
			{  html.setPage( e.getURL() );
			}
			catch( IOException ioe )
			{	System.out.println( "Can't load url: " + url );
				System.exit( 0 );
			}
		}
	}
}