Invoking JavaScript from Java

Posted by Geertjan on Oracle Blogs See other posts from Oracle Blogs or by Geertjan
Published on Sun, 1 Jul 2012 11:49:02 +0000 Indexed on 2012/07/01 15:20 UTC
Read the original article Hit count: 173

Filed under:

Here's an Action class defined in Java. The Action class executes a script via the JavaFX WebEngine:

@NbBundle.Messages("CTL_AddBananasAction=Add Banana")
private class AddBananasAction extends AbstractAction {
    public AddBananasAction() {
        super(Bundle.CTL_AddBananasAction());
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                webengine.executeScript("addBanana(' " + newBanana + " ') ");
            }
        });
    }
}
How does the 'executescript' call know where to find the JavaScript file? Well, earlier in the code, the WebEngine loaded an HTML file, where the JavaScript file was registered:
WebView view = new WebView();
view.setMinSize(widthDouble, heightDouble);
view.setPrefSize(widthDouble, heightDouble);
webengine = view.getEngine();
URL url = getClass().getResource("home.html");
webengine.load(url.toExternalForm());

Finally, here's a skeleton 'addBanana' method, which is invoked via the Action class shown above:

function addBanana(user){
    statustext.text(user);
}

By the way, if you have your JavaScript and CSS embedded within your HTML file, the code navigator combines all three into the same window, which is kind of cool:

© Oracle Blogs or respective owner

Related posts about /NetBeans IDE