Java -创建web浏览器



我正在java中创建一个web浏览器,当我试图运行它时收到以下错误:

Exception in thread "main" java.net.MalformedURLException: no protocol:

我还没能找到我这个特殊问题的答案,但我相信这和我的插座有关。我只需要添加一个malformmedurlexception吗?如有任何帮助,不胜感激。

import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Browser extends JFrame {
    public JPanel addressPanel, windowPanel;
    public JLabel addressLabel;
    public JTextField textField;
    public JEditorPane windowPane;
    public JScrollPane windowScroll;
    public JButton addressButton;
    private Search search = new Search();
    public Browser() throws IOException {
        addressLabel = new JLabel(" address: ", SwingConstants.CENTER);
        textField = new JTextField("Enter a web address..");
        textField.addActionListener(search);
        addressButton = new JButton("Go");
        addressButton.addActionListener(search);
        windowPane = new JEditorPane("");
        windowPane.setContentType("text/html");
        windowPane.setEditable(false);
        addressPanel = new JPanel(new BorderLayout());
        windowPanel = new JPanel(new BorderLayout());
        addressPanel.add(addressLabel, BorderLayout.WEST);
        addressPanel.add(textField, BorderLayout.CENTER);
        addressPanel.add(addressButton, BorderLayout.EAST);
        windowScroll = new JScrollPane(windowPane);
        windowPanel.add(windowScroll);
        Container pane = getContentPane();
        pane.setLayout(new BorderLayout());
        pane.add(addressPanel, BorderLayout.NORTH);
        pane.add(windowPanel, BorderLayout.CENTER);
        setTitle("Web Browser");
        setSize(1000, 1000);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public class Search implements ActionListener {
        public void actionPerformed(ActionEvent ea) {
            String line;
            try {
                Socket socket = new Socket(textField.getText(), 80);
                PrintWriter out = new PrintWriter(socket.getOutputStream());
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out.print("GET / HTTP/1.1rn");
                out.print(textField.getText() + "rnrn");
                out.flush();
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws IOException {
        Browser browser = new Browser();
    }
}

问题出在下面一行:

windowPane = new JEditorPane("");

改成

windowPane = new JEditorPane();


根据JEditorPane构造函数javadoc:

根据包含URL规范的字符串创建JEditorPane
@param url url
@exception IOException如果URL是null或无法访问

相关内容

  • 没有找到相关文章

最新更新