今天在網上找了好久如何用在java swing開啟網頁,從而實現顯示網頁圖表的效果,功夫不負有心人,終於搞定了,下面把所用的類和swt.jar整理了一下,方便有需要的朋友使用。
用到的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);