天天看點

java 編寫浏覽器_java編寫浏覽器

以前采用vb的webbrowser插件可以開發一個簡單的浏覽器,沒想到java也具備這個功能。不過開發出來的看起來比較傻。看來不是java應該做的事情。或許是java還需要編寫更多的代碼來解析css和js

package com.javaer.examples.awt;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Container;

import java.io.IOException;

import javax.swing.JEditorPane;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.event.HyperlinkEvent;

import javax.swing.event.HyperlinkListener;

import javax.swing.text.html.HTMLDocument;

import javax.swing.text.html.HTMLFrameHyperlinkEvent;

public class WebView extends JFrame implements HyperlinkListener{

public WebView() throws Exception {

setSize(640, 480); setTitle(‘‘百度:中國最大的搜尋引擎‘‘);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JEditorPane editorPane = new JEditorPane();

JScrollPane scrollPane = new JScrollPane(editorPane);

editorPane.setEditable(false);

//要能響應網頁中的連結,則必須加上超鍊監聽器

editorPane.addHyperlinkListener(this);

String path = ‘‘http://www.baidu.com‘‘;

try

{

editorPane.setPage(path);

}

catch (IOException e)

{

System.out.println(‘‘讀取頁面 ‘‘ + path + ‘‘ 出錯. ‘‘ + e.getMessage());

}

Container container = getContentPane();

container.setBackground(Color.WHITE);

//讓editorPane總是填滿整個窗體

container.add(scrollPane, BorderLayout.CENTER);

}

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

WebView wv = new WebView();

wv.setVisible(true);

}

//超鍊監聽器,處理對超級連結的點選事件,但對按鈕的點選還捕獲不到

@Override

public void hyperlinkUpdate(HyperlinkEvent e)

{

if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)

{

JEditorPane pane = (JEditorPane) e.getSource();

if (e instanceof HTMLFrameHyperlinkEvent)

{

HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;

HTMLDocument doc = (HTMLDocument) pane.getDocument();

doc.processHTMLFrameHyperlinkEvent(evt);

}

else

{

try

{

pane.setPage(e.getURL());

}

catch (Throwable t)

{

t.printStackTrace();

}

}

}

}

}