XULRunner with Java: JavaXPCOM Tutorial 2
package es.ladyr.javaxpcom.browser; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.ProgressListener; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.mozilla.interfaces.*; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.SWTError; public class SimpleBrowser { public static void main(String args[]) { final Browser browser; Display display = new Display(); Shell shell = new Shell(display); shell.setSize(800, 600); shell.open(); //Initiating the browser using SWT try { browser = new Browser(shell, SWT.MOZILLA); } catch (SWTError e) { System.out.println("Could not instantiate Browser: " + e.getMessage()); return; } // Adapt browser size to shell size browser.setBounds(shell.getClientArea()); // Load an URL into the web browser browser.setUrl("http://www.google.com"); // Listens for page loading status. browser.addProgressListener(new ProgressListener() { public void changed(ProgressEvent event) { } public void completed(ProgressEvent event) { nsIWebBrowser webBrowser = (nsIWebBrowser)browser.getWebBrowser(); nsIDOMWindow window = webBrowser.getContentDOMWindow(); nsIDOMDocument document = window.getDocument(); System.out.println(document); } }); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } }?
4 在java代码里嵌入Firefox3
? 现在可以去用一下有用的例子了。首先我们在一个java程序里使用SWT来嵌入一个Mozilla浏览器。现在,我们可以使用
org.eclipse.swt.browser.Browser类来实例化:browser = new Browser(shell, SWT.MOZILLA); 在这之前,我们需要使用ATF项目
,以及一下ATF插件。非常幸运,现在我们不需要这些补丁了。
4.1 配置环境
? 为了在java程序里嵌入Mozilla浏览器,我们需要使用SWT来创建窗口和嵌入浏览器。
? 4.1.1 安装swt
?? 下载对应操作系统的swt,加到classpath就好了
? 4.1.2 配置swt
?? 运行后面例子需要的jar包:
?? javaxpcom.jar
?? MozillaInterfaces.jar
?? MozillaGlue.jar
?? swt.jar
?? src.zip
4.2 Web Browser例子
?
接下来,我们将增加一下SWT widgets来实现通常的交换,比如输入url,前进与后退,菜单,和两种类型:
? 传入一个参数制定XULRunner的路径
? 不传入参数使用系统安装的XULRunner
package es.ladyr.javaxpcom.browser; import java.io.IOException; import java.io.InputStream; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.ProgressListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; public class LadyrBrowser { private static final int WIDTH = 800; private static final int HEIGHT = 600; Browser browser; private Combo uriCombo; private final ToolItem backItem; private final ToolItem forwardItem; /** * * @param xulrunnerPath if you have a XULRunner valid version in your system, but not * installed, you can use that version to run the browser. This param must contain * its path, or null in other case. */ public LadyrBrowser(String xulrunnerPath) { Display display = new Display(); Shell shell = new Shell(display); shell.setSize(WIDTH, HEIGHT); GridLayout gridLayout = new GridLayout(1, true); shell.setLayout(gridLayout); // Set the menu bar // create the menu Menu menuBar = new Menu(shell, SWT.BAR); // create a file menu and add an exit item final MenuItem file = new MenuItem(menuBar, SWT.CASCADE); file.setText("&File"); final Menu filemenu = new Menu(shell, SWT.DROP_DOWN); file.setMenu(filemenu); final MenuItem exitMenuItem = new MenuItem(filemenu, SWT.PUSH); exitMenuItem.setText("&Exit/tCTRL+E"); exitMenuItem.setAccelerator(SWT.CTRL + 'E'); exitMenuItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { System.exit(0); } }); // create a Help menu and add an about item final MenuItem helpMenuItem = new MenuItem(menuBar, SWT.CASCADE); helpMenuItem.setText("&Help"); final Menu helpmenu = new Menu(shell, SWT.DROP_DOWN); helpMenuItem.setMenu(helpmenu); final MenuItem aboutMenuItem = new MenuItem(helpmenu, SWT.PUSH); aboutMenuItem.setText("&About"); shell.setMenuBar(menuBar); // Set the toolbar ToolBar toolbar = new ToolBar(shell, SWT.FLAT); backItem = new ToolItem(toolbar, SWT.PUSH); backItem.setImage(getImage("resources/back.png")); backItem.setEnabled(false); forwardItem = new ToolItem(toolbar, SWT.PUSH); forwardItem.setImage(getImage("resources/forward.png")); forwardItem.setEnabled(false); backItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (browser.isBackEnabled()) { browser.back(); } } }); forwardItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (browser.isForwardEnabled()) { browser.forward(); } } }); final ToolItem refreshItem = new ToolItem(toolbar, SWT.PUSH); refreshItem.setImage(getImage("resources/refresh.png")); refreshItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { browser.refresh(); } }); final ToolItem stopItem = new ToolItem(toolbar, SWT.PUSH); stopItem.setImage(getImage("resources/stop.png")); stopItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { browser.stop(); } }); uriCombo = new Combo(toolbar, SWT.NONE); uriCombo.setItems(new String[] { "www.ladyr.com", "www.urjc.es", "www.mozilla.org" }); uriCombo.setText("http://www.google.es"); uriCombo.setBounds(0, 0, 3 * (WIDTH / 4), 0); uriCombo.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { Combo c = (Combo) e.widget; browser.setUrl(c.getText()); System.out.println(c.getText()); } public void widgetDefaultSelected(SelectionEvent e) { Combo c = (Combo) e.widget; browser.setUrl(c.getText()); System.out.println(c.getText()); } }); final ToolItem uriComboItem = new ToolItem(toolbar, SWT.SEPARATOR); uriComboItem.setWidth(uriCombo.getSize().x); uriComboItem.setControl(uriCombo); final ToolItem goItem = new ToolItem(toolbar, SWT.PUSH); goItem.setImage(getImage("resources/go.png")); goItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { browser.setUrl(uriCombo.getText()); } }); GridData data = new GridData(); data.horizontalAlignment = SWT.FILL; toolbar.setLayoutData(data); toolbar.pack(); // Set the page visualization area Canvas canvas = new Canvas(shell, SWT.BORDER); data = new GridData(); // Set the same dimensions than shell, after we will call pack method // to fit the canvas size to the shell size. data.horizontalAlignment = SWT.FILL; data.verticalAlignment = SWT.FILL; data.widthHint = WIDTH; data.heightHint = HEIGHT; canvas.setLayoutData(data); shell.pack(); shell.open(); // Browser code initMozillaBrowser(uriCombo.getText(), canvas, xulrunnerPath); // End of browser code while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } /** * * @param uri * @param canvas * @param xulrunnerPath if you have a XULRunner valid version in your system, but not * installed, you can use that version to run the browser. This param must contain * its path, or null in other case. */ private void initMozillaBrowser(String uri, Canvas canvas, String xulrunnerPath) { browser = new Browser(canvas, SWT.MOZILLA); //nsIWebBrowser webBrowser = (nsIWebBrowser)browser.getWebBrowser(); browser.setBounds(canvas.getClientArea()); browser.setUrl(uri); browser.addProgressListener(new ProgressListener() { public void changed(ProgressEvent event) { uriCombo.setText(browser.getUrl()); updateToolItemsState(); } public void completed(ProgressEvent event) { updateToolItemsState(); } }); } private Image getImage(String path) { InputStream sourceStream = this.getClass().getResourceAsStream(path); ImageData source = new ImageData(sourceStream); Image image = new Image(null, source); try { sourceStream.close(); } catch (IOException e) { e.printStackTrace(); } return image; } private void updateToolItemsState() { if (!backItem.isEnabled() && browser.isBackEnabled()) { backItem.setEnabled(true); } else if (backItem.isEnabled() && !browser.isBackEnabled()) { backItem.setEnabled(false); } if (!forwardItem.isEnabled() && browser.isForwardEnabled()) { forwardItem.setEnabled(true); } else if (forwardItem.isEnabled() && !browser.isForwardEnabled()) { forwardItem.setEnabled(false); } } public static void main(String[] args) { if (args.length > 0) { new LadyrBrowser(args[0]); } else { new LadyrBrowser(null); } } }?
5. 在浏览器里访问JavaXPCOM
?? 这一节里我们将讨论一下通过WebBrowser访问的功能。比如,改变浏览器的属性或者观察浏览器请求与响应。
?? 首先我们改变用户的preferences
?? 注:我只列出增加的部分代码。
?
public class SimpleBrowserWithPrefs { // Obtain preferences service String contractID = "@mozilla.org/preferences-service;1"; nsIPrefService prefService = (nsIPrefService) serviceManager .getServiceByContractID(contractID, nsIPrefService.NS_IPREFSERVICE_IID); // Get a branch to access to the entire preference tree nsIPrefBranch branch = prefService.getBranch(""); // Set some preferences // Warn before submitting a form to an insecure area ? -> False branch.setBoolPref("security.warn_submit_insecure", 0); // Select direction of text: // 1 : Left-to-right // 2 : Right-to-left branch.setIntPref("bidi.direction", 2); // Allow current document to specify colors to use? // (If false, background images will also not be loaded) branch.setBoolPref("browser.display.use_document_colors", 0); }?
另外一下Service也能被使用。我们已经可以改变Mozilla的属性来改变浏览器的行为,但是通过利用Service我们可以完成更有用的
任务。在下面的例子里我们将观察浏览器的请求和响应。在XPCOM里存在一个接口叫nsIObserver,它运行观察一个topic相关的event
,只要它被添加到observer Service里了。添加的方法是使用 void nsIObserverService.addObserver(nsIObserver anObserver,
String aTopic, boolean ownsWeak) 这个方法对一个特定的topic注册一个listener。anObserver是用来接受通知的一个接口,
aTopic是通知的topic,ownsWeak当nsIObserverService hold anObserver的一个strong的引用时设为false,否则设置为true。因此
,为了创建一个observer,我们必需实现nsIObserver接口,这个接口包含了一个方法 public void observe(nsISupports
aSubject, String aTopic, String aData)。
下面的例子的4个步骤:
? 1,获得Service Manager
? 2,获得Observer Service
? 3,创建一个简单的HTTP observer
? 4,把这个observer添加到监听请求和响应的Service里