在 Java Swing 中嵌入 Firefox 浏览器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2020854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Embed Firefox browser in Java Swing
提问by Mountain
I am wondering if it is possible to embed Firefox browser as a component in a Java Swing based application.
我想知道是否可以将 Firefox 浏览器作为组件嵌入基于 Java Swing 的应用程序中。
I have done a bit of research from the Internet, but I could not find an answer. Some people suggest to use other browser component available in Java. I do not think that is preferable, as the rendering engine would be different to Firefox.
我从互联网上做了一些研究,但我找不到答案。有些人建议使用 Java 中可用的其他浏览器组件。我不认为这是可取的,因为渲染引擎与 Firefox 不同。
Any idea? Many thanks.
任何的想法?非常感谢。
采纳答案by Greg
Absolutely I have done it before please check out the Mozilla Embedding for Java
绝对我已经完成了,请查看Mozilla Embedding for Java
Here is some sample code
这是一些示例代码
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.*;
import org.mozilla.xpcom.*;
import org.mozilla.interfaces.*;
/*
Websites ref
http://groups.google.com/group/mozilla.dev.tech.java/browse_thread/thread/898ba6751d0c57f7
http://skrul.com/blog/code/
http://wirestorm.net/blog/?cat=9
*/
public class BrowserTest implements nsIWebProgressListener,nsIWeakReference, nsIInterfaceRequestor, nsIWebBrowserChrome, nsISHistoryListener{
static {
try {
System.loadLibrary("NativeWindow");
} catch (UnsatisfiedLinkError e) {
System.err.println("can't find your library");
}
}
private static final String frameTitle="GRE Embedded";
public static void main(String[] args) {
BrowserConroller controler=new BrowserConroller();
controler.run();
new BrowserTest().start();
}
public void start(){
JFrame f = new JFrame( frameTitle );
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JLabel("Initializing ... "));
f.setVisible(true);
File grePath = null;
LocationProvider locProvider;
Mozilla mozilla = Mozilla.getInstance();
GREVersionRange[] range = new GREVersionRange[1];
range[0] = new GREVersionRange("1.8.0", true, "1.9", false);
try {
grePath = Mozilla.getGREPathWithProperties(range, null);
mozilla.initialize(grePath);
locProvider = new LocationProvider(grePath);
mozilla.initEmbedding(grePath, grePath, locProvider);
}
catch (FileNotFoundException e) {
System.out.println("Error: FileNotFoundException");
}
catch (XPCOMException e) {
System.out.println("Error: XPCOMException");
}
//---------- END GRE INITIALIZATION------------
nsIServiceManager serviceManager = mozilla.getServiceManager();
nsIAppStartup appStartup = (nsIAppStartup)serviceManager.getServiceByContractID("@mozilla.org/toolkit/app-startup;1", nsIAppStartup.NS_IAPPSTARTUP_IID);
nsIWindowCreator windowCreator = (nsIWindowCreator)appStartup.queryInterface(nsIWindowCreator.NS_IWINDOWCREATOR_IID);
nsIWindowWatcher windowWatcher =(nsIWindowWatcher)serviceManager.getServiceByContractID("@mozilla.org/embedcomp/window-watcher;1",nsIWindowWatcher.NS_IWINDOWWATCHER_IID);
windowWatcher.setWindowCreator(windowCreator);
nsIDOMWindow win = windowWatcher.openWindow(null, "http://google.com", "MAIN_WIN","chrome,resizable,centerscreen", null);
windowWatcher.setActiveWindow( win );
nsIComponentManager componentManager = mozilla.getComponentManager();
String NS_IWEBBROWSER_CID = "F1EAC761-87E9-11d3-AF80-00A024FFC08C"; //$NON-NLS-1$
nsIWebBrowser webBrowser = (nsIWebBrowser) componentManager.createInstance(NS_IWEBBROWSER_CID, null, nsIWebBrowser.NS_IWEBBROWSER_IID);
webBrowser.setContainerWindow(this);
webBrowser.addWebBrowserListener(this, nsIWebProgressListener.NS_IWEBPROGRESSLISTENER_IID);
// nsIWebNavigation webNavigation=(nsIWebNavigation)webBrowser.queryInterface(nsIWebNavigation.NS_IWEBNAVIGATION_IID);
// webNavigation.loadURI("http://www.zdnet.com", nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);
//
nsIBaseWindow baseWindow = (nsIBaseWindow) webBrowser.queryInterface(nsIBaseWindow.NS_IBASEWINDOW_IID);
long handle=FindWindow.getHWND( frameTitle );
baseWindow.initWindow(handle, 0, 0, 0,350,350);
baseWindow.create();
baseWindow.setVisibility(true);
//
// nsIDOMWindow domWin=webBrowser.getContentDOMWindow();
// nsIDOMEventTarget domEventTarget= (nsIDOMEventTarget)domWin.queryInterface(nsIDOMEventTarget.NS_IDOMEVENTTARGET_IID);
// domEventTarget.addEventListener("click", new EventListener(), false);
//
//Hide JFrame after it have been initialized
f.setVisible(true);
//
// nsIWebNavigation webNavigation=(nsIWebNavigation)webBrowser.queryInterface(nsIWebNavigation.NS_IWEBNAVIGATION_IID);
// webNavigation.loadURI("http://www.zdnet.com", nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);
//
appStartup.run();
System.out.println("try termEmbedding");
try {
System.out.println("mozilla.termEmbedding(); START");
mozilla.termEmbedding();
System.out.println("mozilla.termEmbedding(); FINISHED");
}
catch (XPCOMException e) {
System.out.println("Fehler: XPCOMException");
}
System.out.println("finished termEmbedding");
System.out.println("All done");
}
public void onLocationChange(nsIWebProgress webProgress, nsIRequest request, nsIURI location) {
c("onLocationChange");
}
public void onProgressChange(nsIWebProgress webProgress, nsIRequest request, int curSelfProgress, int maxSelfProgress, int curTotalProgress, int maxTotalProgress) {
c("onProgressChange");
}
public void onSecurityChange(nsIWebProgress webProgress, nsIRequest request, long state) {
c("onSecurityChange");
}
public void onStateChange(nsIWebProgress webProgress, nsIRequest request, long stateFlags, long status) {
c("onStateChange");
}
public void onStatusChange(nsIWebProgress webProgress, nsIRequest request, long status, String message) {
c("onStatusChange");
}
public nsISupports queryInterface(String uuid) {
c("queryInterface");
return null;
}
public nsISupports queryReferent(String uuid) {
c("queryReferent");
return null;
}
public nsISupports getInterface(String uuid) {
c("getInterface");
return null;
}
private void c(Object o){
System.out.println(o);
}
public void destroyBrowserWindow() {
c("destroyBrowserWindow");
}
public void exitModalEventLoop(long status) {
c("exitModalEventLoop");
}
public long getChromeFlags() {
c("getChromeFlags");
return 0;
}
public nsIWebBrowser getWebBrowser() {
c("getWebBrowser");
return null;
}
public boolean isWindowModal() {
c("isWindowModal");
return false;
}
public void setChromeFlags(long chromeFlags) {
c("setChromeFlags");
}
public void setStatus(long statusType, String status) {
c("setStatus");
}
public void setWebBrowser(nsIWebBrowser webBrowser) {
c("setWebBrowser");
}
public void showAsModal() {
c("showAsModal");
}
public void sizeBrowserTo(int acx, int acy) {
c("sizeBrowserTo");
}
public boolean onHistoryGoBack(nsIURI backURI) {
c("onHistoryGoBack");
return false;
}
public boolean onHistoryGoForward(nsIURI forwardURI) {
c("onHistoryGoForward");
return false;
}
public boolean onHistoryGotoIndex(int index, nsIURI gotoURI) {
c(" onHistoryGotoIndex");
return false;
}
public void onHistoryNewEntry(nsIURI newURI) {
c(" onHistoryNewEntry");
}
public boolean onHistoryPurge(int numEntries) {
c(" onHistoryPurge");
return false;
}
public boolean onHistoryReload(nsIURI reloadURI, long reloadFlags) {
c(" onHistoryReload");
return false;
}
} //public class JavaXPCOM_test1[/code]
回答by Aaron Digulla
Not directly. You could port your UI (or at least part of it) to SWT and then use the Browser component (see this FAQ item).
不直接。您可以将您的 UI(或至少其中的一部分)移植到 SWT,然后使用浏览器组件(请参阅此 FAQ 项)。
If you can't port your UI to SWT, then you canembed your Swing UI in SWT (SWT Shell
== Swing JFrame
). But there will be some pain ahead.
如果您不能将您的 UI 移植到 SWT,那么您可以将您的 Swing UI 嵌入到 SWT 中(SWT Shell
== Swing JFrame
)。但是前面会有一些痛苦。
Update:Firefox is no longer supported by SWT. Currently supported is the system's default browser or WebKit (see https://github.com/eclipse/eclipse.platform.swt/search?q=BrowserFactory&unscoped_q=BrowserFactory).
更新:SWT 不再支持 Firefox。当前支持的是系统的默认浏览器或 WebKit(参见https://github.com/eclipse/eclipse.platform.swt/search?q=BrowserFactory&unscoped_q=BrowserFactory)。
回答by Mark
A quick Google search returns a product called JxBrowserthat does this.
一个快速的谷歌搜索会返回一个名为JxBrowser的产品。
However, I would question whether you really need a full blown browser component like Firefox in your application. What do you need it for in your application?
但是,我会质疑您是否真的需要在您的应用程序中使用一个完整的浏览器组件,例如 Firefox。您在应用程序中需要它做什么?
回答by Adriaan Koster
How about embedding your GUI inside the browser instead, with an applet, GWT or another rich client approach?
将您的 GUI 嵌入到浏览器中如何,使用小程序、GWT 或其他富客户端方法?
回答by alfonx
As answered here (Best Java/Swing browser component?)- and from my own testing - djprojectseems to be the best.
正如这里所回答的(最佳 Java/Swing 浏览器组件?)- 从我自己的测试来看- djproject似乎是最好的。
It has last been updated March 2009 and some demo links are broken.. so the project seems not to be too active right now.. Still: When I needed it in 2010 it was awesome.
它最后一次更新是在 2009 年 3 月,并且一些演示链接已损坏.. 所以该项目现在似乎不太活跃.. 不过:当我在 2010 年需要它时,它很棒。