Source of MiniBrowserGUIApp.java


  1: //MiniBrowserGUIApp.java
  2: //Retrieves a file from a web server as raw text.

  4: import java.awt.*;
  5: import java.awt.event.*;
  6: import java.net.*;
  7: import java.io.*;
  8: import javax.swing.*;

 10: public class MiniBrowserGUIApp extends JFrame
 11: implements ActionListener
 12: {
 13:     private JTextField textInput;
 14:     private TextArea contents;
 15:     private JButton displayButton;

 17:     public static void main(String [] args)
 18:     {
 19:         MiniBrowserGUIApp app = new MiniBrowserGUIApp();
 20:         app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 21:         app.makeGUI();
 22:         app.setSize(550, 370);
 23:         app.setVisible(true);
 24:     }

 26:     public void makeGUI()
 27:     {
 28:         getContentPane().setLayout(new FlowLayout());

 30:         textInput = new JTextField(40);
 31:         getContentPane().add(textInput);
 32:         displayButton = new JButton("Enter a full URL above and click " +
 33:                                     "here to display that page below:");
 34:         getContentPane().add(displayButton);

 36:         contents = new TextArea("", 20, 60,
 37:                                 TextArea.SCROLLBARS_VERTICAL_ONLY);
 38:         getContentPane().add(contents);
 39:         displayButton.addActionListener(this);
 40:     }
 41: 
 42:     public void actionPerformed(ActionEvent event)
 43:     {
 44:         String line;
 45:         String location = textInput.getText();

 47:         try
 48:         {
 49:             contents.setText("");
 50:             URL url = new URL(location);
 51:             BufferedReader input = new
 52:                 BufferedReader(new InputStreamReader(url.openStream()));
 53:             while ((line = input.readLine()) != null)
 54:             {
 55:                  contents.append(line);
 56:                  contents.append("\n");
 57:             }
 58:             input.close();
 59:             contents.setCaretPosition(0);
 60:         }
 61:         catch (MalformedURLException e)
 62:         {
 63:             contents.setText("Error: Invalid URL format.");
 64:         }
 65:         catch (IOException io)
 66:         {
 67:             contents.setText("Error: " + io.toString());
 68:         }
 69:     }
 70: }