简体   繁体   English

如何在nashorn中转换Java类?

[英]How to cast java classes in nashorn?

In my application I use javafx and I have a WebView that shows news from website. 在我的应用程序中,我使用javafx,并且有一个WebView可以显示来自网站的新闻。 When any link is clicked inside of this WebView - it should open it in browser, not in WebView. 当单击此WebView内部的任何链接时,应在浏览器中而不是WebView中打开它。 I found code that should work in java: 我发现应该在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);
        }

But the trick is, that i need to translate it to js(using nashron engine). 但是诀窍是,我需要将其翻译为js(使用nashron引擎)。 Here what i have for the moment: 这是我目前所拥有的:

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();
                    }
                )
            }
        }
    });

I found some Java.to() and Java.type() , but I didn't find out how to cast using them(not sure if it is possible at all). 我找到了一些Java.to()Java.type() ,但是我没有找到如何使用它们进行转换(不确定是否可以实现)。 Could anyone give me some advise, please? 有人可以给我一些建议吗?

When you are using JavaScript, you do not need to cast your objects. 使用JavaScript时,不需要强制转换对象。 So just call the function on the object. 因此,只需在对象上调用该函数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM