Sunday Jul 01, 2012

Invoking JavaScript from Java

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:

About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« July 2012 »
SunMonTueWedThuFriSat
14
28
29
30
31
    
       
Today