SimpleBrowser.java

This application uses JEditorPane to display the contents of a file on a web server. The user enters a URL in the JTextField at the top of the window, and the application displays the corresponding document (if it exists) in the JEditorPane.

The application also demonstrates how to process HyperlinkEvents when the user clicks a hyperlink in the HTML document. and notifies all registered HyperlinkListeners (package javax.swing.event) of that event.

If a JEditorPane contains an HTML document and the user clicks a hyperlink, the JEditorPane generates a HyperlinkEvent and notifies all registered HyperlinkListeners of that event.

Notice there is no “back” button to return to a previous page.


SimpleBrowser.java

// Reading a file by opening a connection through a URL.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class SimpleBrowser extends JFrame 
{
   private JTextField enter;   // JTextField to enter site name
   private JEditorPane area; // to display website

   // set up GUI
   public SimpleBrowser()
   {
      super("Simple Web Browser");

      // create enter and register its listener
      enter = new JTextField("Enter file URL here");
     enter.addActionListener(event -> getThePage(event.getActionCommand()));

      add(enter, BorderLayout.NORTH);

      area = new JEditorPane(); // create area
      area.setEditable(false);
      area.addHyperlinkListener(event -> {
               if (event.getEventType() == 
                    HyperlinkEvent.EventType.ACTIVATED)
                  getThePage(event.getURL().toString());
});

      add(new JScrollPane(area), BorderLayout.CENTER);
      setSize(400, 300); // set size of window
      setVisible(true); // show window
   }

   // load document
   private void getThePage(String location)
   {
      try // load document and display location 
      {
         area.setPage(location); // set the page
         enter.setText(location); // set the text
      } 
      catch (IOException ioException) 
      {
         JOptionPane.showMessageDialog(this,
            "Error retrieving specified URL", "Bad URL", 
            JOptionPane.ERROR_MESSAGE);
      } 
   }

   public static void main(String[] args)
   {
      SimpleBrowser application = new SimpleBrowser();
      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   } 

} 


Maintained by John Loomis, updated Mon Apr 27 10:31:18 2020