// File: Browser3.java
// Tim Balls : Sept 1999
// Adds a scroll area to the display
// Add a text input field to allow user to enter URL
// Needs changes to display - to incorporate input field
// and additional event handling
// Command line parameter is now optional
// 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.*;
import java.awt.*;
public class Browser3 extends JFrame implements HyperlinkListener,
ActionListener
{ public static void main( String[] args )
{ if( args.length == 0 )
{ new Browser3( "NoURL" );
}
else
{ new Browser3( args[0] );
}
}
private JEditorPane html = new JEditorPane();
private URL url;
private JTextField location;
public Browser3( String site )
{ setSize( 350, 450 );
setTitle( "Scrolling Browser" );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e )
{ System.exit( 0 );
}
});
// Build more interesting interface
location = new JTextField( site, 25 ); // 25 cols
JPanel topLine = new JPanel();
topLine.setLayout( new FlowLayout( FlowLayout.LEFT ) );
topLine.add( new JLabel( "URL:" ) );
topLine.add( location );
location.addActionListener( this );
// for the JFrame:
this.getContentPane().setLayout( new BorderLayout() );
this.getContentPane().add( topLine, BorderLayout.NORTH );
if( !site.equals( "NoURL" ) )
{ loadURL( site );
}
JScrollPane scroller = new JScrollPane();
JViewport viewport = scroller.getViewport();
viewport.add( html );
this.getContentPane().add( scroller, BorderLayout.CENTER );
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 );
}
}
// update text field
location.setText( "" + e.getURL() );
}
// When a new URL is entered (and return pressed)
public void actionPerformed( ActionEvent e )
{ String site = location.getText();
loadURL( site );
// big assumption - it is legal and works!!
}
// Attempt to load the html JEditorPane from the URL at "site"
private void loadURL( String site )
{ try
{ url = new URL( site );
}
catch( MalformedURLException e )
{ System.out.println( "Invalid URL specified" );
System.exit( 0 );
}
try
{ html.setPage( url ); // load page
}
catch( IOException e )
{ System.out.println( "Can't load url: " + url );
System.exit( 0 );
}
}
} |