// File: Browser2.java
// Tim Balls : Sept 1999
// Adds a scroll area to the display
// Displays the contents of a URL
// Can follow hyperlinks
// Uses Swing classes : JFrame and JEditorPane
// Adds JScrollPane - a controller for a JViewPort
import javax.swing.*;
import javax.swing.event.*;
import java.net.*;
import java.io.IOException;
import java.awt.event.*;
public class Browser2 extends JFrame implements HyperlinkListener
{ public static void main( String[] args )
{ new Browser2( args[0] );
}
private JEditorPane html;
private URL url;
public Browser2( String site )
{ setSize( 350, 450 );
setTitle( "Scrolling 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 );
}
JScrollPane scroller = new JScrollPane();
JViewport viewport = scroller.getViewport();
viewport.add( html );
getContentPane().add( scroller );
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 );
}
}
}
} |