Search code examples
javafx-2fxml

Is It Possible To Import Classes into FXML <fx:script> block (JavaFX-2)


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 ...


Solution

  • Use javascript build-in importPackage or importClass functions.

     <fx:script>
        importPackage(java.lang);
        function buttonAction(event){
            System.out.println("finally we get to print something.");
        }
    </fx:script>
    

    For more details, see: http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html#jsimport