I'm trying out JavaFX-2 and one of the features is said to be that we can create event handler functions using Javascript in our FXML file. One thing that bugged me is I can't access the System class right away. It needs to be fully referenced, like "java.lang.System". That becomes ugly when we need a simple output on the console, I mean come on, "System.out.println" is ugly enough to get something printed. And, even though my FXML has all the <?import java.lang.*?> statements, apparently it doesn't affect inside of the <fx:script> tags.
Sample code: (Notice the <?language javascript?>
directive)
<?xml version="1.0" encoding="UTF-8"?>
<?language javascript?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<AnchorPane fx:id="rootPane">
<fx:script>
function buttonAction(event){
java.lang.System.out.println("finally we get to print something.");
// System.out.println("This wouldn't work even if it wasn't a comment line, anyway");
}
</fx:script>
<children>
<Button id="close" mnemonicParsing="false" onAction="buttonAction(event)" text="">
<graphic>
<ImageView pickOnBounds="true">
<image>
<Image url="@../resources/close.png" preserveRatio="true" smooth="true" />
</image>
</ImageView>
</graphic>
</Button>
</children>
</AnchorPane>
So my question is: Is there any way to import classes into <fx:script>? I remember I was doing this in Actionscript3.0 really easy: import flash.events.MouseEvent
...
Use javascript build-in
importPackage
orimportClass
functions.For more details, see: http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html#jsimport
This is all a bit confusing but the link from Sergey gives good context to what's going on in the background (ie extending java into the scripting world).
Although Sergey's solution works, it mixes java class methods inside the inline script which is presumably meant to be javascript (as per the page language declaration). There's no browser, so no "console.log()", so maybe it would be best to avoid the potential java/js confusion and just use print():
The next question is where does the print() method originate from .... it's not java and it's not js. The answer I think lies in the Nashorn javascript engine used to underpin the java/js integration. Print() is a built-in function: Nashorn shell commands.