1

I'm using FXML documents to define JavaFX layouts and have been using Java controllers but am now looking at javascript event handlers directly in the FXML documents.

I'm wondering if anyone knows how to call a Javascript function defined in a FXML document from the application?

ie given a FXML document F.FXML

<BorderPane>
  <fx:script>
     function something() {}
  </fx:script>
</BorderPane>

thats loaded by FXMLLoader:

FXMLLoader fxml = new FXMLLoader("F.FXML");
BorderPane root = (BorderPane)fxml.load();

is it possible to do the equivalent of:

root.something()

I guess the work around is to do some magic with a controller class behind the scenes but i'd still like to define the functions in javascript.

Daniel Walton
  • 113
  • 1
  • 11

1 Answers1

1

Take a look at this tutorial on working with JavaFX with Javascript

public class MapApp extends Application {
    public static int ZOOM_STREET = 10;

    public static class City {
        public City(String name) {...}
        ...
    }

    public int currentZipCode;

    public void navigateTo(City location, int zoomLevel) {...}
     ....
}

and the javascript:

function navigateTo(cityName) {
   //Assumes that the Ant task uses "myMapApp" as id for this application
   var mapApp = document.getElementById("myMapApp");
   if (mapApp != null) {
       //City is nested class. Therefore classname uses $ char 
       var city = new mapApp.Packages.testapp.MapApp$City(cityName);
       mapApp.navigateTo(city, mapApp.Packages.testapp.MapApp.ZOOM_STREET);
       return mapApp.currentZipCode;
   }
   return "unknown";
}
window.alert("Area zip: " + navigateTo("San Francisco"));

As explained by the tutorial:

The JavaScript snippet in [above] passes several values to the Java code [above the javascript snippet]. Before these values are used in the Java code, they are automatically converted to the closest Java type.

Cobbles
  • 1,748
  • 17
  • 33
  • Thanks for the answer but unfortuantely thats not where i want to get the java and javascript talking. This is between javascript in a web page and java in an embedded javafx applet. The same is possible between a web page in a WebView in the JavaFX scene graph. This doesn't apply to the JavaScript in a FXML view. – Daniel Walton Jun 17 '14 at 23:21