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

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class MiniBrowserGUIApp extends JFrame
implements ActionListener
{
    private JTextField textInput;
    private TextArea contents;
    private JButton displayButton;

    public static void main(String [] args)
    {
        MiniBrowserGUIApp app = new MiniBrowserGUIApp();
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.makeGUI();
        app.setSize(550, 370);
        app.setVisible(true);
    }

    public void makeGUI()
    {
        getContentPane().setLayout(new FlowLayout());

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

        contents = new TextArea("", 20, 60,
                                TextArea.SCROLLBARS_VERTICAL_ONLY);
        getContentPane().add(contents);
        displayButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
        String line;
        String location = textInput.getText();

        try
        {
            contents.setText("");
            URL url = new URL(location);
            BufferedReader input = new
                BufferedReader(new InputStreamReader(url.openStream()));
            while ((line = input.readLine()) != null)
            {
                 contents.append(line);
                 contents.append("\n");
            }
            input.close();
            contents.setCaretPosition(0);
        }
        catch (MalformedURLException e)
        {
            contents.setText("Error: Invalid URL format.");
        }
        catch (IOException io)
        {
            contents.setText("Error: " + io.toString());
        }
    }
}
