6/26/10

Reading file from browser

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

public class ReadServerFile extends JFrame {

    private JTextField textField;
    private JEditorPane editorPane;
// for application execution

    public static void main(String args[]) {
        new ReadServerFile();
    }
    // set up GUI

    public ReadServerFile() {
        super("Simple Web Browser");
        Container container = getContentPane();
        // create textField and register its listener
        textField = new JTextField("Enter file URL here");
        textField.addActionListener(
                new ActionListener() {
                    // get document specified by user

                    public void actionPerformed(ActionEvent event) {
                        getThePage(event.getActionCommand());
                    }
                } // end anonymous inner class
                ); // end call to addActionListener
        container.add(textField, BorderLayout.NORTH);
        // create editorPane and register HyperlinkEventlistener
        editorPane = new JEditorPane();
        editorPane.setEditable(false);
        editorPane.addHyperlinkListener(
                new HyperlinkListener() {
                    // if user clicked hyperlink, go to specified page

                    public void hyperlinkUpdate(HyperlinkEvent event) {
                        if (event.getEventType() ==
                                HyperlinkEvent.EventType.ACTIVATED) {
                            getThePage(event.getURL().toString());
                        }
                    }
                } // end anonymous inner class
                ); // end call to addHyperlinkListener
        container.add(new JScrollPane(editorPane),
                BorderLayout.CENTER);
        setSize(400, 300);
        setVisible(true);
        setDefaultCloseOperation(
                DISPOSE_ON_CLOSE);
    }

    // load document; change mouse cursor to indicate status
    private void getThePage(String strURL) {
        setCursor(Cursor.getPredefinedCursor(
                Cursor.WAIT_CURSOR));
        // load document into editorPane and display strURL in  textField
        try {
            editorPane.setPage(strURL);
            textField.setText(strURL);
        } // process problems loading document
        catch (IOException ioException) {
            JOptionPane.showMessageDialog(this,
                    "Error retrieving specified URL",
                    "Bad URL",
                    JOptionPane.ERROR_MESSAGE);
        }
        setCursor(Cursor.getPredefinedCursor(
                Cursor.DEFAULT_CURSOR));
    }
}

No comments:

Post a Comment

Popular Posts