/** * A Simple Web Browser * Uses a JEditorPane() which knows how to interpret HTML (and RTF and Text) **/ // Lots of imports! import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.html.HTMLFrameHyperlinkEvent; import javax.swing.text.html.HTMLDocument; public class SimpleBrowser extends JFrame { /// Fields /** A field for the URL to be entered **/ private JTextField urlField; private JEditorPane webpane; /*** * Most of the action is in the constructor. **/ public SimpleBrowser(){ super("Simple Browser"); // Make a panel with a label and the URL field JPanel panel1=new JPanel(); this.getContentPane().add(panel1,BorderLayout.NORTH); JLabel label1= new JLabel("URL:"); panel1.add(label1,BorderLayout.EAST); urlField = new JTextField("http://www.cnn.com"); urlField.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { String urlString = e.getActionCommand(); try { webpane.setPage(urlString); urlField.setText(urlString); } catch (Exception e2) { System.out.println("I/O Error -- maybe bad URL?"); System.out.println(e2.getMessage());} } }); panel1.add(urlField,BorderLayout.CENTER); // Second part of the browser is the viewable pane webpane = new JEditorPane(); webpane.setEditable(false); // Make hyperlinks work (from 1.4JDK docs) webpane.addHyperlinkListener( new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane pane = (JEditorPane) e.getSource(); if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; HTMLDocument doc = (HTMLDocument)pane.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { try { pane.setPage(e.getURL()); } catch (Throwable t) { t.printStackTrace(); } } } } }); this.getContentPane().add(new JScrollPane(webpane), BorderLayout.CENTER); this.pack(); this.setVisible(true); } public void loadPage(String urlString){ try { webpane.setPage(urlString); urlField.setText(urlString); } catch (Exception e) { System.out.println("I/O Error -- maybe bad URL?"); System.out.println(e.getMessage());} } } // Class