djnative_djnativeswing - CSDN
精华内容
参与话题
  • DJNativeSwing:java内嵌浏览器的常用方法 最近用到了java内嵌浏览器DJNativeSwing,在此总结一下DJNativeSwing的常用方法,方便将来查找使用,如有不足欢迎批评指正。 1.需要的jar包: DJNativeSwing.jar  ...

    DJNativeSwing:java内嵌浏览器的常用方法

    最近用到了java内嵌浏览器DJNativeSwing,在此总结一下DJNativeSwing的常用方法,方便将来查找使用,如有不足欢迎批评指正。

    1.需要的jar包:
    DJNativeSwing.jar 
    DJNativeSwing-SWT.jar 
    swt-4.3-win32-win32-x86-1.7.0_11-b21.jar

    2.用到的import语句:
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;

    import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
    import chrriis.dj.nativeswing.swtimpl.components.WebBrowserFunction;

    3.创建java浏览器窗口的相关方法:
    (1)创建一个类,继承JFrame
    (2)在这个类中创建一个方法,使用以下语句进行窗口相关设置:

    //窗口标题
    this.setTitle("我的浏览器窗口");
    //窗口大小
    this.setSize(1400, 700);
    //点击窗口右上角自带的关闭按钮后,调用任意已注册 WindowListener 的对象后自动隐藏并释放该窗体
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //注册窗口关闭事件监听器(可自定义窗口关闭事件)
    this.addWindowListener(new WindowAdapter()
            {
                @Override
                public void windowClosed(WindowEvent event)
                {
                        //关闭窗口
                        super.windowClosed(event);
                }

            });

    /*------------------------------------------------------------*/

    //创建JWebBrowser对象
    JWebBrowser webBrowser = new JWebBrowser(JWebBrowser.destroyOnFinalization());
    //设置为不显示菜单
    webBrowser.setMenuBarVisible(false);
    //在JFrame的中间添加JWebBrowser对象
    this.add(webBrowser, BorderLayout.CENTER);
    //创建JWebBrowser需要的自定义监听器对象
    //(实际上WebBrowserAdapter类实现了WebBrowserListener接口,可以新建类继承WebBrowserAdapter,重写相应方法,之后注册,实现自定义监听)
    WebBrowserAdapter adapter = new WebBrowserAdapter();
    //注册这个监听器
    webBrowser.addWebBrowserListener(adapter);

    /*------------------------------------------------------------*/

    //以下是通过注册自定义方法webBrowser.registerFunction()实现重写js方法
    try
            {
                //该方法是为了避免在EDT中执行长时间的操作导致页面卡住,将一个任务放到EDT线程中,EDT会在适当的时候进行调用。
                //与invoikeLater的相同点:都可以把可运行对象排入事件派发线程的队列中。
                //不同点:invokeLater在把可运行的对象放入队列后就返回,而invokeAndWait一直等待知道已启动了可运行的run方法才返回。
                SwingUtilities.invokeAndWait(new Runnable()
                {
                    
                    @Override
                    public void run()
                    {
                        //注册自定义方法"alert"
                        webBrowser.registerFunction(new WebBrowserFunction("alert")
                        {
                            @Override
                            public Object invoke(JWebBrowser arg0, Object... arg1)
                            {
                                System.out.println("jwebBrowser弹出alert框,内容是:" + arg1[0] + "");
                                return null;
                            }
                        });
                        //注册自定义方法"confirm"
                        webBrowser.registerFunction(new WebBrowserFunction("confirm")
                        {
                            @Override
                            public Object invoke(JWebBrowser arg0, Object... arg1)
                            {
                                System.out.println("webBrowser弹出confirm框:" + providerCode + "");
                                return null;
                            }
                        });
                    }
                });
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            catch (InvocationTargetException e)
            {
                e.printStackTrace();
            }

    /*------------------------------------------------------------*/

    //创建面板容器对象jPanel,居中
    JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    //创建按钮对象,传入按钮名
    JButton jButton = new JButton("我的按钮");
    //按钮大小
    jButton.setSize(50, 20);
    //在jPanel中添加按钮
    jPanel.add(jButton, BorderLayout.WEST);    
    //在按钮上注册监听器
    jButton.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    System.out.println("点击按钮后输入这句话");
                }
            });        
    /*------------------------------------------------------------*/        
    //设置为可见
    this.setVisible(true);
    //总是置顶
    this.setAlwaysOnTop(true);        
    //显示在前方
    this.toFront();

    (3)创建这个类的对象,就可以看到java浏览器窗口了。

    (4)补充:

    还有一个使用@PostConstruct注解配置的方法,会在Servlet初始化后、init方法前执行。在一个@Component("DJNative")标注的自己创建的类DJNative.java中。

    @PostConstruct
    public void initNativeSwing() {
       System.out.println("DJNativeSwing-setPreferredLookAndFeel");
       UIUtils.setPreferredLookAndFeel();
       System.out.println("DJNativeSwing-open");
       NativeInterface.open();
       System.out.println("DJNativeSwing初始化成功");
    }

    也就是说,在创建这个类的对象之前,要执行NativeInterface.open();方法,不然会报错。例如:

    public static void main(String[] args) {
           //UIUtils.setPreferredLookAndFeel();
           NativeInterface.open();
           //创建继承JFrame类的View类对象       
           new View();
    }
    

     

    4.JWebBrowser常用方法:

    //创建JWebBrowser对象
    JWebBrowser webBrowser = new JWebBrowser(JWebBrowser.destroyOnFinalization());
    //导航到指定网址
    webBrowser.navigate("www.baidu.com");
    //传入自定义html文本
    webBrowser.setHTMLContent("<html><span>我是自定义HTML</span></html>

    //执行js方法
    webBrowser.executeJavascript("console.log('我是js')");
    //执行js方法,有返回值
    webBrowser.executeJavascriptWithResult("console.log('我是js')");
    //源码中获取cookie信息的方法
    public static String getCookie(String url, String name) {
            return webBrowserStatic.getCookie(url, name);
        }
    //实际获取cookie信息的方法    
    SwingUtilities.invokeAndWait(new Runnable()
                {
                    @Override
                    public void run( )
                    {
                        String cookieValue = webBrowser.getCookie(webBrowser.getResourceLocation(), cookieName);
                    }
                });    

    //源码中设置cookie信息的方法
    public static void setCookie(String url, String value) {
            webBrowserStatic.setCookie(url, value);
        }

    5.WebBrowserEvent常用方法,该对象在JWebBrowser的监听器中出现
    //监听器中的对象
     WebBrowserEvent e;
    //得到页面加载进度,100时加载完毕
    e.getWebBrowser().getLoadingProgress() == 100
        
    6.js常用方法:

    //自定义网页离开事件
    window.οnbefοreunlοad=null;    

    //自定义alert方法
    window.alert = function(msg){
    console.log(msg);
    };

    //获取当前页面状态
    return document.readyState;
    该属性返回以下值:
    uninitialized - 还未开始载入
    loading - 载入中
    interactive - 已加载,文档与用户可以开始交互
    complete - 载入完成

    //设置剪贴板的内容
    clipboardData.setData('text', '');
    //读出当前剪贴板里的内容
    clipboardData.getData('text');
     

    展开全文
  • 只有这个支持js,css,但是网页超过一定高度,就会截取一半; 如果是接口调用的话,因为是线程,所以这个只能运行一次就自动关闭了;使用main方法运行就没有问题 引入依赖包: &lt;dependency&...
    • 只有这个支持js,css,但是网页超过一定高度,就会截取一半;
    • 如果是接口调用的话,因为是线程,所以这个只能运行一次就自动关闭了;使用main方法运行就没有问题
    • 引入依赖包:
    <dependency>
       <groupId>com.hynnet</groupId>
       <artifactId>DJNativeSwing</artifactId>
       <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.hynnet</groupId>
        <artifactId>DJNativeSwing-SWT</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.swt.org.eclipse.swt.win32.win32.x86_64.4.3.swt</groupId>
        <artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
        <version>4.3</version>
    </dependency>
    • 案例:

    1.首先在springboot启动页上重写方法:

    @SpringBootApplication
    public class DjnativeswingApplication {
    
        public static void main(String[] args) {
            SpringApplicationBuilder builder = new SpringApplicationBuilder(DjnativeswingApplication.class);
            ApplicationContext applicationContext = builder.headless(false).run(args);
            applicationContext.getBean(TestController.class);
    //        SpringApplication.run(DjnativeswingApplication.class, args);
        }
    
    }

    2.写一个工具类:

    public class DjNativeSwingUtil extends JPanel {
        private static final long serialVersionUID = 1L;
        // 行分隔符
        final static public String LS = System.getProperty("line.separator", "/n");
        // 文件分割符
        final static public String FS = System.getProperty("file.separator", "//");
        // 当网页超出目标大小时 截取
        final static public int maxWidth = 2000;
        final static public int maxHeight = 1600;
    
    //    private static class ExitTrappedException extends SecurityException { }
    
    //    private static void forbidSystemExitCall() {
    //        final SecurityManager securityManager = new SecurityManager() {
    //            public void checkPermission( Permission permission ) {
    //                if( "exitVM".equals( permission.getName() ) ) {
    //                    throw new ExitTrappedException() ;
    //                }
    //            }
    //        } ;
    //        System.setSecurityManager( securityManager ) ;
    //    }
    
        public  DjNativeSwing(final String file, final String url, final String WithResult) {
            super(new BorderLayout());
            JPanel webBrowserPanel = new JPanel(new BorderLayout());
            final JWebBrowser webBrowser = new JWebBrowser(null);
            webBrowser.setBarsVisible(false);
            webBrowser.navigate(url);
            webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
            add(webBrowserPanel, BorderLayout.CENTER);
            JPanel panel = new JPanel(new FlowLayout());
            webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
                // 监听加载进度
                public void loadingProgressChanged(WebBrowserEvent e) {
                    // 当加载完毕时
                    if (e.getWebBrowser().getLoadingProgress() == 100) {
                        String result = (String) webBrowser.executeJavascriptWithResult(WithResult);
                        int index = result == null ? -1 : result.indexOf(":");
                        NativeComponent nativeComponent = webBrowser.getNativeComponent();
                        Dimension originalSize = nativeComponent.getSize();
                        Dimension imageSize = new Dimension(Integer.parseInt(result.substring(0, index)),
                                Integer.parseInt(result.substring(index + 1)));
                        imageSize.width = Math.max(originalSize.width, imageSize.width + 50);
                        imageSize.height = Math.max(originalSize.height, imageSize.height + 50);
                        nativeComponent.setSize(imageSize);
                        BufferedImage image = new BufferedImage(imageSize.width, imageSize.height,
                                BufferedImage.TYPE_INT_RGB);
                        nativeComponent.paintComponent(image);
                        nativeComponent.setSize(originalSize);
                        // 当网页超出目标大小时
    //                    if (imageSize.width > maxWidth || imageSize.height > maxHeight) {
    //                        // 截图部分图形
    //                        image = image.getSubimage(0, 0, maxWidth, maxHeight);
    //                        // 此部分为使用缩略图
    //                        /*
    //                         * int width = image.getWidth(), height = image
    //                         * .getHeight(); AffineTransform tx = new
    //                         * AffineTransform(); tx.scale((double) maxWidth /
    //                         * width, (double) maxHeight / height);
    //                         * AffineTransformOp op = new AffineTransformOp(tx,
    //                         * AffineTransformOp.TYPE_NEAREST_NEIGHBOR); //缩小 image
    //                         * = op.filter(image, null);
    //                         */
    //                    }
                        try {
                            // 输出图像
                            ImageIO.write(image, "png", new File(file));
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        // 退出操作
                        System.exit(0);//关闭jvm同时也关闭了tomcat
                    }
                }
            });
            add(panel, BorderLayout.SOUTH);
        }
    
        // 以javascript脚本获得网页全屏后大小
        public static String getScreenWidthHeight() {
    
            StringBuffer jsDimension = new StringBuffer();
            jsDimension.append("var width = 0;").append(LS);
            jsDimension.append("var height = 0;").append(LS);
            jsDimension.append("if(document.documentElement) {").append(LS);
            jsDimension.append("  width = Math.max(width, document.documentElement.scrollWidth);").append(LS);
            jsDimension.append("  height = Math.max(height, document.documentElement.scrollHeight);").append(LS);
            jsDimension.append("}").append(LS);
            jsDimension.append("if(self.innerWidth) {").append(LS);
            jsDimension.append("  width = Math.max(width, self.innerWidth);").append(LS);
            jsDimension.append("  height = Math.max(height, self.innerHeight);").append(LS);
            jsDimension.append("}").append(LS);
            jsDimension.append("if(document.body.scrollWidth) {").append(LS);
            jsDimension.append("  width = Math.max(width, document.body.scrollWidth);").append(LS);
            jsDimension.append("  height = Math.max(height, document.body.scrollHeight);").append(LS);
            jsDimension.append("}").append(LS);
            jsDimension.append("return width + ':' + height;");
    
            return jsDimension.toString();
        }
    }

    3. 截取的代码:

    @Configuration
    public class TestController {
        public static boolean printUrlScreen2jpg(final String file, final String url, final int width, final int height) {
            NativeInterface.open();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    String withResult = "var width = " + width + ";var height = " + height + ";return width +':' + height;";
                    if (width == 0 || height == 0)
                        withResult = DjNativeSwing.getScreenWidthHeight();
    
                    JFrame frame = new JFrame("网页截图");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    // 加载指定页面,最大保存为640x480的截图
                    frame.getContentPane().add(new DjNativeSwing(file, url, withResult), BorderLayout.CENTER);
                    frame.setSize(640, 800);
                    // 仅初始化,但不显示
                    frame.invalidate();
    
                    frame.pack();
                    frame.setVisible(false);
                }
            });
            NativeInterface.runEventPump();
            return true;
        }
    }
    

    4.接口调用:

      @RequestMapping(value = "/htmltest", produces = "application/json;charset=UTF-8")
        @ResponseBody
        public String htmlGenerator() throws Exception{
            TestController.printUrlScreen2jpg("G:/网页截图.png", "G:/index.html", 1000, 1300);
            return null;
        }

    展开全文
  • java内嵌浏览器DJNativeSwing的jar包DJNativeSwing.jar DJNativeSwing-SWT.jar 以及32位和64位的SWT.jar
  • java内嵌浏览器DJNativeSwing

    千次阅读 2013-10-01 11:10:12
    由于一个项目的需要,必须在程序中嵌入一个浏览器来完成用户的一些操作,研究了几天之后本人决定使用DJ NativeSwing这个控件,该空间需要使用以下jar包支持 1.DJNativeSwing.jar 2.DJNativeSwing-SWT.jar ...

    由于一个项目的需要,必须在程序中嵌入一个浏览器来完成用户的一些操作,研究了几天之后本人决定使用DJ NativeSwing这个控件,该空间需要使用以下jar包支持

    1.DJNativeSwing.jar

    2.DJNativeSwing-SWT.jar

    3.org.eclipse.swt.win32.win32.x86_64_3.100.1.v4236b.jar 或者 org.eclipse.swt.win32.win32.x86_3.102.0.v20130605-1544

    下载地址(免积分下载):http://download.csdn.net/detail/shikai2008/6344335

    其中前两个为必须jar包,第三个根据操作系统选择自己合适的jar包即可。

    前期工作做好之后就可以编写自己的代码了。

    import java.awt.BorderLayout;
    
    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;
    import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
    import chrriis.dj.nativeswing.swtimpl.components.WebBrowserEvent;
    
    public class Test extends JPanel {
    
    	private static final long serialVersionUID = 1L;
    
    	private JPanel webBrowserPanel;
    
    	private JWebBrowser webBrowser;
    
    	// private String url;
    
    	public Test(String url) {
    		super(new BorderLayout());
    		this.url = url;
    		webBrowserPanel = new JPanel(new BorderLayout());
    		webBrowser = new JWebBrowser();
    		webBrowser.navigate(url);
    		webBrowser.setButtonBarVisible(false);
    		webBrowser.setMenuBarVisible(false);
    		webBrowser.setBarsVisible(false);
    		webBrowser.setStatusBarVisible(false);
    		webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
    		add(webBrowserPanel, BorderLayout.CENTER);
    		// webBrowser.executeJavascript("javascrpit:window.location.href='http://www.baidu.com'");
    		 webBrowser.executeJavascript("alert('haha')"); //执行Js代码
    	}
    
    	public static void main(String[] args) {
    		final String url = "http://www.baidu.com";
    		final String title = "DJ NativeSwiting Test";
    		UIUtils.setPreferredLookAndFeel();
    		NativeInterface.open();
    
    		SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				JFrame frame = new JFrame(title);
    				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				frame.getContentPane().add(new Test(url), BorderLayout.CENTER);
    				frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    				frame.setLocationByPlatform(true);
    				frame.setVisible(true);
    			}
    		});
    		NativeInterface.runEventPump();
    	}
    
    }

    至此,你的java代码中就可以嵌入浏览器了


    展开全文
  • 今天要说的额是浏览器的第一个版本是用DJnative-swt和swt包开发的调用本地浏览器和webkit浏览器的示例 这是我的工程目录【源码见最后】:   src下为写的源码,lib为引入的swt和DJnative和mozilla接口...

    Java-Swing嵌入浏览器(一)

    今天要说的额是浏览器的第一个版本是用DJnative-swt和swt包开发的调用本地浏览器和webkit浏览器的示例

    这是我的工程目录【源码见最后】:

    image

     

    src下为写的源码,lib为引入的swt和DJnative和mozilla接口包~

    我们来看两个类,此两个类是嵌入webkiet mozilla的内核浏览器 要用到xulrunner

    这里有一句代码 就是下面这句

    //指定xulRunner路径 如不指定就调用系统注册的xulrunner 注册为 xulRunner目录下的xulrunner --register-global
            NSSystemPropertySWT.WEBBROWSER_XULRUNNER_HOME.set(System.getProperty("user.dir") + "/xulrunner");

    如果没有写这句代码引入工程下的xulrunner,那么就必须要进行注册注册为xulrunner --register-global 卸载为 xulrunner --unregister-global

    XPCOMDownloadManager.java 类 调用mozilla内核浏览器

    复制代码
    /*
     * luwenbin006@163.com (luwenbin006@163.com)
     * http://www.luwenbin.com
     *
     * See the file "readme.txt" for information on usage and redistribution of
     * this file, and for a DISCLAIMER OF ALL WARRANTIES.
     */
    package com.luwenbin.webbrowser;
    
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    import org.mozilla.interfaces.nsICancelable;
    import org.mozilla.interfaces.nsIComponentRegistrar;
    import org.mozilla.interfaces.nsIFactory;
    import org.mozilla.interfaces.nsILocalFile;
    import org.mozilla.interfaces.nsIMIMEInfo;
    import org.mozilla.interfaces.nsIRequest;
    import org.mozilla.interfaces.nsISupports;
    import org.mozilla.interfaces.nsITransfer;
    import org.mozilla.interfaces.nsIURI;
    import org.mozilla.interfaces.nsIWebProgress;
    import org.mozilla.interfaces.nsIWebProgressListener;
    import org.mozilla.xpcom.Mozilla;
    
    import chrriis.common.UIUtils;
    import chrriis.dj.nativeswing.swtimpl.NSSystemPropertySWT;
    import chrriis.dj.nativeswing.swtimpl.NativeInterface;
    import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
    import chrriis.dj.nativeswing.swtimpl.components.MozillaXPCOM;
    
    /**
     * @author luwenbin006@163.com
     */
    public class XPCOMDownloadManager
    {
    
        public static JComponent createContent()
        {
            JPanel contentPane = new JPanel(new BorderLayout());
            JPanel webBrowserPanel = new JPanel(new BorderLayout());
            webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));
            //指定xulRunner路径 如不指定就调用系统注册的xulrunner 注册为 xulRunner目录下的xulrunner --register-global
            NSSystemPropertySWT.WEBBROWSER_XULRUNNER_HOME.set(System.getProperty("user.dir") + "/xulrunner");
    
            final JWebBrowser webBrowser = new JWebBrowser(JWebBrowser.useXULRunnerRuntime());
            webBrowser.navigate("http://www.eclipse.org/downloads");
            webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
            contentPane.add(webBrowserPanel, BorderLayout.CENTER);
            // Create an additional area to see the downloads in progress.
            final JPanel downloadsPanel = new JPanel(new GridLayout(0, 1));
            downloadsPanel.setBorder(BorderFactory.createTitledBorder("Download manager (on-going downloads are automatically added to this area)"));
            contentPane.add(downloadsPanel, BorderLayout.SOUTH);
            // We can only access XPCOM when it is properly initialized.
            // This happens when the web browser is created so we run our code in sequence.
            webBrowser.runInSequence(new Runnable()
            {
                public void run()
                {
                    try
                    {
                        nsIComponentRegistrar registrar = MozillaXPCOM.Mozilla.getComponentRegistrar();
                        String NS_DOWNLOAD_CID = "e3fa9D0a-1dd1-11b2-bdef-8c720b597445";
                        String NS_TRANSFER_CONTRACTID = "@mozilla.org/transfer;1";
                        registrar.registerFactory(NS_DOWNLOAD_CID, "Transfer", NS_TRANSFER_CONTRACTID, new nsIFactory()
                        {
                            public nsISupports queryInterface(String uuid)
                            {
                                if(uuid.equals(nsIFactory.NS_IFACTORY_IID) || uuid.equals(nsIFactory.NS_ISUPPORTS_IID))
                                {
                                    return this;
                                }
                                return null;
                            }
                            public nsISupports createInstance(nsISupports outer, String iid)
                            {
                                return createTransfer(downloadsPanel);
                            }
                            public void lockFactory(boolean lock) {}
                        });
                    }
                    catch(Exception e)
                    {
                        JOptionPane.showMessageDialog(webBrowser, "Failed to register XPCOM download manager.\nPlease check your XULRunner configuration.", "XPCOM interface", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                }
            });
            return contentPane;
        }
    
        private static nsITransfer createTransfer(final JPanel downloadsPanel)
        {
            return new nsITransfer()
            {
                public nsISupports queryInterface(String uuid)
                {
                    if(uuid.equals(nsITransfer.NS_ITRANSFER_IID) ||
                            uuid.equals(nsITransfer.NS_IWEBPROGRESSLISTENER2_IID) ||
                            uuid.equals(nsITransfer.NS_IWEBPROGRESSLISTENER_IID) ||
                            uuid.equals(nsITransfer.NS_ISUPPORTS_IID))
                    {
                        return this;
                    }
                    return null;
                }
                private JComponent downloadComponent;
                private JLabel downloadStatusLabel;
                private String baseText;
                public void init(nsIURI source, nsIURI target, String displayName, nsIMIMEInfo MIMEInfo, double startTime, nsILocalFile tempFile, final nsICancelable cancelable)
                {
                    downloadComponent = new JPanel(new BorderLayout(5, 5));
                    downloadComponent.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
                    JButton cancelDownloadButton = new JButton("Cancel");
                    downloadComponent.add(cancelDownloadButton, BorderLayout.WEST);
                    final String path = target.getPath();
                    cancelDownloadButton.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                            cancelable.cancel(Mozilla.NS_ERROR_ABORT);
                            removeDownloadComponent();
                            new File(path + ".part").delete();
                        }
                    });
                    baseText = "Downloading to " + path;
                    downloadStatusLabel = new JLabel(baseText);
                    downloadComponent.add(downloadStatusLabel, BorderLayout.CENTER);
                    downloadsPanel.add(downloadComponent);
                    downloadsPanel.revalidate();
                    downloadsPanel.repaint();
                }
                public void onStateChange(nsIWebProgress webProgress, nsIRequest request, long stateFlags, long status)
                {
                    if((stateFlags & nsIWebProgressListener.STATE_STOP) != 0)
                    {
                        removeDownloadComponent();
                    }
                }
                private void removeDownloadComponent()
                {
                    downloadsPanel.remove(downloadComponent);
                    downloadsPanel.revalidate();
                    downloadsPanel.repaint();
                }
                public void onProgressChange64(nsIWebProgress webProgress, nsIRequest request, long curSelfProgress, long maxSelfProgress, long curTotalProgress, long maxTotalProgress)
                {
                    long currentKBytes = curTotalProgress / 1024;
                    long totalKBytes = maxTotalProgress / 1024;
                    downloadStatusLabel.setText(baseText + " (" + currentKBytes + "/" + totalKBytes + ")");
                }
                public void onStatusChange(nsIWebProgress webProgress, nsIRequest request, long status, String message) {}
                public void onSecurityChange(nsIWebProgress webProgress, nsIRequest request, long state) {}
                public void onProgressChange(nsIWebProgress webProgress, nsIRequest request, int curSelfProgress, int maxSelfProgress, int curTotalProgress, int maxTotalProgress) {}
                public void onLocationChange(nsIWebProgress webProgress, nsIRequest request, nsIURI location) {}
            };
        }
    
        /* Standard main method to try that test as a standalone application. */
        public static void main(String[] args)
        {
            NativeInterface.open();
            UIUtils.setPreferredLookAndFeel();
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    JFrame frame = new JFrame("DJ Native Swing Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.getContentPane().add(createContent(), BorderLayout.CENTER);
                    frame.setSize(800, 600);
                    frame.setLocationByPlatform(true);
                    frame.setVisible(true);
                }
            });
            NativeInterface.runEventPump();
        }
    
    }
    复制代码

    下面是运行效果:

    image

    XPCOMToggleEditionModer.java 类 调用mozilla内核浏览器 并启用编辑模式

    复制代码
    /*
     * luwenbin006@163.com (luwenbin006@163.com)
     * http://www.luwenbin.com
     *
     * See the file "readme.txt" for information on usage and redistribution of
     * this file, and for a DISCLAIMER OF ALL WARRANTIES.
     */
    package com.luwenbin.webbrowser;
    
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    
    import javax.swing.BorderFactory;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    import org.mozilla.interfaces.nsIDOMDocument;
    import org.mozilla.interfaces.nsIDOMNSHTMLDocument;
    import org.mozilla.interfaces.nsIDOMWindow;
    import org.mozilla.interfaces.nsIWebBrowser;
    
    import chrriis.common.UIUtils;
    import chrriis.dj.nativeswing.swtimpl.NSSystemPropertySWT;
    import chrriis.dj.nativeswing.swtimpl.NativeInterface;
    import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
    import chrriis.dj.nativeswing.swtimpl.components.MozillaXPCOM;
    
    /**
     * @author luwenbin006@163.com
     */
    public class XPCOMToggleEditionMode
    {
    
        public static JComponent createContent()
        {
            JPanel contentPane = new JPanel(new BorderLayout());
            JPanel webBrowserPanel = new JPanel(new BorderLayout());
            webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));
            //指定xulRunner路径 如不指定就调用系统注册的xulrunner 注册为 xulRunner目录下的xulrunner --register-global
            NSSystemPropertySWT.WEBBROWSER_XULRUNNER_HOME.set(System.getProperty("user.dir") + "/xulrunner");
    
            final JWebBrowser webBrowser = new JWebBrowser(JWebBrowser.useXULRunnerRuntime());
            webBrowser.navigate("http://www.google.com");
            webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
            contentPane.add(webBrowserPanel, BorderLayout.CENTER);
            // Create an additional bar allowing to toggle the edition mode of the web browser.
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));
            JCheckBox designModeCheckBox = new JCheckBox("Edition Mode (allows to type text or resize elements directly in the page)");
            designModeCheckBox.addItemListener(new ItemListener()
            {
                public void itemStateChanged(ItemEvent e)
                {
                    nsIWebBrowser iWebBrowser = MozillaXPCOM.getWebBrowser(webBrowser);
                    if(iWebBrowser == null)
                    {
                        JOptionPane.showMessageDialog(webBrowser, "The XPCOM nsIWebBrowser interface could not be obtained.\nPlease check your XULRunner configuration.", "XPCOM interface", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    nsIDOMWindow window = iWebBrowser.getContentDOMWindow();
                    nsIDOMDocument document = window.getDocument();
                    nsIDOMNSHTMLDocument nsDocument = (nsIDOMNSHTMLDocument)document.queryInterface(nsIDOMNSHTMLDocument.NS_IDOMNSHTMLDOCUMENT_IID);
                    nsDocument.setDesignMode(e.getStateChange() == ItemEvent.SELECTED ? "on" : "off");
                }
            });
            buttonPanel.add(designModeCheckBox);
            contentPane.add(buttonPanel, BorderLayout.SOUTH);
            return contentPane;
        }
    
        /* Standard main method to try that test as a standalone application. */
        public static void main(String[] args)
        {
            NativeInterface.open();
            UIUtils.setPreferredLookAndFeel();
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    JFrame frame = new JFrame("DJ Native Swing Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.getContentPane().add(createContent(), BorderLayout.CENTER);
                    frame.setSize(800, 600);
                    frame.setLocationByPlatform(true);
                    frame.setVisible(true);
                }
            });
            NativeInterface.runEventPump();
        }
    
    }
    复制代码

    下面是运行效果:

    image

    SimpleWebBrowserExample.java 调用本机默认浏览器

    复制代码
    /*
     * luwenbin006@163.com (luwenbin006@163.com)
     * http://www.luwenbin.com
     *
     * See the file "readme.txt" for information on usage and redistribution of
     * this file, and for a DISCLAIMER OF ALL WARRANTIES.
     */
    package com.luwenbin.webbrowser;
    
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    
    import javax.swing.BorderFactory;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    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;
    
    /**
     * @author luwenbin006@163.com
     */
    public class SimpleWebBrowserExample
    {
    
        public static JComponent createContent()
        {
            JPanel contentPane = new JPanel(new BorderLayout());
            JPanel webBrowserPanel = new JPanel(new BorderLayout());
            webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));
            final JWebBrowser webBrowser = new JWebBrowser();
            webBrowser.navigate("http://www.google.com");
            webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
            contentPane.add(webBrowserPanel, BorderLayout.CENTER);
            // Create an additional bar allowing to show/hide the menu bar of the web browser.
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));
            JCheckBox menuBarCheckBox = new JCheckBox("Menu Bar", webBrowser.isMenuBarVisible());
            menuBarCheckBox.addItemListener(new ItemListener()
            {
                public void itemStateChanged(ItemEvent e)
                {
                    webBrowser.setMenuBarVisible(e.getStateChange() == ItemEvent.SELECTED);
                }
            });
            buttonPanel.add(menuBarCheckBox);
            contentPane.add(buttonPanel, BorderLayout.SOUTH);
            return contentPane;
        }
    
        /* Standard main method to try that test as a standalone application. */
        public static void main(String[] args)
        {
            NativeInterface.open();
            UIUtils.setPreferredLookAndFeel();
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    JFrame frame = new JFrame("DJ Native Swing Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.getContentPane().add(createContent(), BorderLayout.CENTER);
                    frame.setSize(800, 600);
                    frame.setLocationByPlatform(true);
                    frame.setVisible(true);
                }
            });
            NativeInterface.runEventPump();
        }
    
    }
    复制代码

    下面是运行效果:

    image

    展开全文
  • DJNative Swing 之JWebBrowser总结

    千次阅读 2012-11-19 16:47:19
    DJNative Swing 之JWebBrowser总结 1、org.eclipse.swt.SWTError: No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)] SWTError:没有更多的处理[未知Mozilla的路径(MOZILLA_FIVE_HOME未设置...
  • 想做一款软件,界面用H5实现,这样开发效率会非常高,之前用的JAVAFX做的,但是这东西对CSS支持貌似烂的一塌糊涂,所以想改用DJNativeSwing,但是JWebBrowser如何实现js和原生java函数的交互呢?...
  • 相关JAR包 ,一个都不能少 djnativeswing.jar djnativeswing-swt.jar org.eclipse.swt.win32.win32.x86_64-4.2.jar 效果:
  • Swing中富文本实现方案:  openOffce 组件(OOoBean)  详见 ...   ... Ekit 组件 (另一个很不错的swing解决方案) ...
  • CKEditor 3.0.1 在 asp.net 下进行配置的方法: 官方网站:CKEditor(Fully functional, open source editor, with source code included)下载地址:CKEditor 3.0.1(released on 16 October 2009)1、下载 ...
  • 原因是Jar包在Modulepath里。 更改为Classpath后即可解决。 右键工程文件==》Buid Path==》ConfigureBuid Path..==》Libraries
  • 使用到了DJNative (一种JAVA浏览器实现http://sourceforge.net/projects/djproject/files/DJ%20Native%20Swing/0.9.9%20preview/DJNativeSwing-SWT-0-9-9-20110224.zip/download),对于一些进行接口开发的业务整合...
  • 相关推荐

    2012-01-11 12:17:19
    相关推荐 ...使用到了DJNative (一种JAVA浏览器实现http://sourceforge.net/projects/djproject/files/DJ %20Native%20Swing/0.9.9%20preview/DJNativeSwing-SWT -0-9-9-20110224.zip/download...
  • Java-Swing嵌入浏览器

    千次阅读 2017-08-18 16:32:44
    今天要说的额是浏览器的第一个版本是用DJnative-swt和swt包开发的调用本地浏览器和webkit浏览器的示例 这是我的工程目录【源码见最后】:   src下为写的源码,lib为引入的swt和DJnative和mozilla...
  • 今天要说的额是浏览器的第一个版本是用DJnative-swt和swt包开发的调用本地浏览器和webkit浏览器的示例 这是我的工程目录【源码见最后】: src下为写的源码,lib为引入的swt和DJnative和mozilla接口包~ 我们来...
  • 转:Java-Swing嵌入浏览器

    千次阅读 2017-06-25 08:35:41
    今天要说的额是浏览器的第一个版本是用DJnative-swt和swt包开发的调用本地浏览器和webkit浏览器的示例 这是我的工程目录【源码见最后】:   src下为写的源码,lib为引入的swt和DJnative和mozilla接口...
  • 思路: 当用户登录完成后,(登录问题请参见,SWING实现新浪微博客户端(1)自动登录功能 ) 1,模拟用户动作自动进入关注好友页面 2,根据关注好友页面结构提取关注好友的用户信息 3,将用户信息发送到后台...
  • 思路: 当用户登录完成后,(登录问题请参见,SWING实现新浪微博客户端(1)自动登录功能 ) 1,模拟用户动作自动进入关注好友页面 2,根据关注好友页面结构提取关注好友的用户信息 3,将用户信息发送到后台,...
  • java内嵌浏览器DJNativeSwing的jar包以及32位和64位的SWT
1 2
收藏数 25
精华内容 10
关键字:

djnative