今天在网上找了好久如何用在java swing打开网页,从而实现显示网页图表的效果,功夫不负有心人,终于搞定了,下面把所用的类和swt.jar整理了一下,方便有需要的朋友使用。
调用网页的Browser要结合现有的java控件使用,一下是结合panel定义的类(SWTPane.java):
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package desktopapplicationmenu.comm;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Panel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
*
* @author liujl
*/
public class SWTPane extends Panel {
DisplayThread displayThread;
private Canvas canvas;
public SWTPane() {
displayThread = new DisplayThread();
displayThread.start();
canvas = new Canvas();
setLayout(new BorderLayout());
add(canvas, BorderLayout.CENTER);
}
public static void main(String args[]) throws Exception {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SWTPane().setVisible(true);
}
});
}
public void addNotify() {
super.addNotify();
Display dis = displayThread.getDisplay();
dis.syncExec(new Runnable() {
public void run() {
Shell shell = SWT_AWT.new_Shell(displayThread.getDisplay(), canvas);
shell.setLayout(new FillLayout());
final Browser browser = new Browser(shell, SWT.NONE);
browser.setLayoutData(BorderLayout.CENTER);
browser.setUrl("http://www.my400800.cn");
}
});
}
}
里面为了防止在打开网页的时候出现错误,封装了一下Thread类,定义如下(DisplayThread.java):
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package desktopapplicationmenu.comm;
import org.eclipse.swt.widgets.Display;
/**
*
* @author liul
*/
public class DisplayThread extends Thread {
private Display display;
Object sem = new Object();
public void run() {
synchronized (sem) {
display = Display.getDefault();
sem.notifyAll();
}
swtEventLoop();
}
private void swtEventLoop() {
while (true) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
public Display getDisplay() {
try {
synchronized (sem) {
while (display == null) {
sem.wait();
}
return display;
}
} catch (Exception e) {
return null;
}
}
}
调用方法
SWTPane jbtn_Sel = new SWTPane();
jPanel1.add(jbtn_Sel);
jbtn_Sel.setBounds(1, 1, 600, 600);