日期:2014-05-20 浏览次数:20681 次
import java.awt.Canvas; import java.awt.Dimension; 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; public class SWTBrowser implements Runnable{ private Canvas canvas; private Display display; private Browser browser; public SWTBrowser(Canvas canvas) { this.canvas = canvas; } public void run(){ display = Display.getDefault(); Shell shell = SWT_AWT.new_Shell(display, canvas); Dimension dim = canvas.getSize (); shell.setSize (dim.width, dim.height); shell.setLayout(new FillLayout()); browser = new Browser(shell,SWT.NONE); shell.layout(); while(!browser.isDisposed()){ if(!display.readAndDispatch()){ display.sleep(); } } } public boolean setUrl(final String url) { if(display==null) return false; ReturnableRunnable rb = new ReturnableRunnable(url); display.syncExec(new Runnable() { public void run() { browser.setUrl(url); } }); return rb.reuslt; } class ReturnableRunnable implements Runnable{ boolean reuslt; String url; ReturnableRunnable(String u){ this.url = u; } public void run() { reuslt = browser.setUrl(url); } } } import java.awt.BorderLayout; import java.awt.Button; import java.awt.Canvas; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class TestSwtBrowser extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private SWTBrowser swtBrowse; public TestSwtBrowser() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 715, 516); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); Button textField = new Button(); textField.setLabel("goto"); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean b = swtBrowse.setUrl("www.baidu.com"); System.out.println(b); } }); contentPane.add(textField, BorderLayout.NORTH); Canvas canvas = new Canvas(); contentPane.add(canvas, BorderLayout.CENTER); swtBrowse = new SWTBrowser(canvas); new Thread(swtBrowse,"SWT-UI-Thread").start(); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { TestSwtBrowser frame = new TestSwtBrowser(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }