2016-10-23 61 views
0

我创建在Java Web浏览器,我收到以下错误,当我尝试运行它:爪哇 - 创建一个Web浏览器

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

我一直没能找到一个答案,我的具体问题但我相信它与我的套接字有关。我只需要添加一个MalformedURLException?任何帮助表示赞赏。

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.1\r\n"); 
       out.print(textField.getText() + "\r\n\r\n"); 
       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(); 
    } 
} 
+1

你需要有该网址的协议。 – Li357

+0

向我们显示您在文本字段中输入的内容。 –

回答

1

问题是因为波纹管行:

windowPane = new JEditorPane(""); 

只是改变

windowPane = new JEditorPane(); 


根据JEditorPane中构造的javadoc:

创建JEditorPane基于包含URL规范的字符串。
@参数的URL网址
抛出IOException - 如果该URL是null或无法访问