如何在nashorn中转换java类?

时间:2017-10-26 13:25:13

标签: javascript java javafx webview nashorn

在我的应用程序中,我使用javafx,我有一个显示网站新闻的WebView。当在WebView中单击任何链接时 - 它应该在浏览器中打开,而不是在WebView中打开。我找到了应该在java中运行的代码:

NodeList nodeList = document.getElementsByTagName("a");
        for (int i = 0; i < nodeList.getLength(); i++)
        {
            Node node= nodeList.item(i);
            EventTarget eventTarget = (EventTarget) node;
            eventTarget.addEventListener("click", new EventListener()
            {
                @Override
                public void handleEvent(Event evt)
                {
                    EventTarget target = evt.getCurrentTarget();
                    HTMLAnchorElement anchorElement = (HTMLAnchorElement) target;
                    String href = anchorElement.getHref();
                    //handle opening URL outside JavaFX WebView
                    System.out.println(href);
                    evt.preventDefault();
                }
            }, false);
        }

但诀窍是,我需要将其转换为js(使用nashron引擎)。这就是我现在所拥有的:

pane.lookup("#newsPane").getEngine().getLoadWorker().stateProperty()["addListener(javafx.beans.value.ChangeListener)"](
    function(o, ov, nv){
        if (nv == javafx.concurrent.Worker.State.SUCCEEDED) {
            // Here the things get started
            var nodes = pane.lookup("#newsPane").getEngine().getDocument().getElementsByTagName("a");
            for(var i=0;i<nodes.getLength();i++){
                var node = nodes.item(i);
                // I got node, but now i need to cast it to EventTarget, but i didn't find anywhere how to do that
                LogHelper.info(node);
                // instead of *node* there should be *eventTarget*, also i'm not sure the code above will work even with EventTarget
                node['addEventListener("click", javafx.event.EventListener)'](
                    function(evt){
                        var target = evt.getCurrentTarget();
                        var href = target.getHref();
                        LogHelper.info(href);
                        evt.preventDefault();
                    }
                )
            }
        }
    });

我找到了一些 Java.to() Java.type(),但我没有找到如何使用它们(不确定是否它是可能的)。请问有人给我一些建议吗?

1 个答案:

答案 0 :(得分:1)

使用JavaScript时,无需转换对象。所以只需在对象上调用函数。