Java项目中经常需要在GUI程序中嵌入浏览器,而Swing自带的组件对CSS、JS的支持不是很好,网上也有很多组件,参考
但是由于对各个平台的支持不是很好,笔者是在Mac系统下进行开发,很多组件只支持在win32,最终选择了开源项目DJNativeSwing-SWT.
代码示例
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
public class Main extends JPanel {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
UIUtils.setPreferredLookAndFeel();
NativeInterface.open();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFrame frame = new JFrame("Ives");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Main(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
NativeInterface.runEventPump();
}
public Main() throws IOException, URISyntaxException {
super(new BorderLayout());
JPanel webBrowserPanel = new JPanel(new BorderLayout());
webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Ives"));
final JWebBrowser webBrowser = new JWebBrowser();
webBrowser.navigate("http://www.t1-network.com");
webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
add(webBrowserPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));
// webBrowser.setBarsVisible(false); //显示前进返回刷新按钮
add(buttonPanel, BorderLayout.SOUTH);
}
}
组件
根据不同的平台及32/64位下载对应Jar包
SWT
Java浏览器组件DJNativeSwing-SWT
注:
mac平台上笔者整理了一套jar包,方便直接下载
下载地址
参考文献
[1] java swing内嵌浏览器 by Geminit
[2]Java内嵌浏览器插件方法( 浏览器组件介绍)
网友评论