Note: Advice in this article will only work for JxBrowser 6. See the corresponding article for JxBrowser 7 here.(注意:本文中的建议仅适用于JxBrowser6,JxBrowser7相应文章请点击这里。)
JxBrowser supports Java Swing. To embed component that displays web pages you need to create Browser instance and wrap it into com.teamdev.jxbrowser.chromium.swing.BrowserView component. The BrowserView is a lightweight component that inherits javax.swing.JComponent. It can be embedded into any Swing container such as JPanel, JWindow, JFrame, etc. (JxBrowser支持Java Swing。要嵌入显示网页的组件,您需要创建浏览器实例并将其包装到com.teamdev.jxbrowser.chromium.swing.BrowserView组件中。 BrowserView是继承javax.swing.JComponent的轻量级组件。它可以嵌入到任何Swing容器中,例如JPanel,JWindow,JFrame等。)
import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.swing.BrowserView; import javax.swing.*; import java.awt.*; /** * This sample demonstrates how to create Browser instance, * embed it into Swing BrowserView container, display it in JFrame and * navigate to the "www.google.com" web site. */ public class BrowserSample { public static void main(String[] args) { Browser browser = new Browser(); BrowserView browserView = new BrowserView(browser); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(browserView, BorderLayout.CENTER); frame.setSize(700, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); browser.loadURL("http://www.google.com"); } }
Important for macOS: On macOS, Chromium engine is initialized in Java process and it will not be uninitialized when last Browser instance is disposed. Chromium engine must be disposed manually after all Browser instances are disposed by using the public static void shutdown()method. This method is invoked asynchronously. Once you shutdown Chromium engine, you cannot use it anymore. Invoke this method only when Java application exits.(对于macOS重要:在macOS上,Chromium引擎是在Java进程中初始化的,并且在处置最后一个Browser实例时不会将其未初始化。使用公共静态void shutdown()方法处理所有浏览器实例后,必须手动处理Chromium引擎。该方法是异步调用的。关闭Chromium引擎后,您将无法再使用它。仅当Java应用程序退出时才调用此方法。)