Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript script in a FXML

I'm trying to run the following example from FXML reference:

This example consists in declaring a String variable in a JavaScript script and using it later in the FXML with the $ operator for displaying the String in a Label.

The problem is that when I run this example with Java 8u40, the Label is empty instead of showing the declared String.

JavaFxComponent.java:

public class JavaFxComponent extends VBox {
    public JavaFxComponent() throws Exception {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/JavaFxComponent.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.load();
    }
}

JavaFxComponent.fxml:

<?xml version="1.0" encoding="UTF-8"?>
<?language javascript?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<fx:root type="javafx.scene.layout.VBox" xmlns="http://javafx.com/javafx/8"
    xmlns:fx="http://javafx.com/fxml">
    <fx:script>
        var myText = "This is the text of my label.";
    </fx:script>
    <Label text="$myText" />
</fx:root>

JavaFxTest:

public class JavaFxTest extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(new JavaFxComponent()));
        primaryStage.show();
    }

    public static final void main(String[] args) {
        launch(args);
    }
}
like image 769
Romain Moreau Avatar asked Jul 21 '15 10:07

Romain Moreau


1 Answers

It seems that "var myText" doesn't create a reference in the scope where '$' performs lookup. This is probably not the answer you were looking for, however I believe it will be useful to mention alternatives for those who stumble upon the same issue, at least until this is resolved or someone sheds more light on the matter.


  1. <fx:define>
         <String fx:id="myText" fx:value="This is the text of my label." /> 
    </fx:define>
    <Label text="$myText" />
    

  2. <Label fx:id="myLabel" />
    <fx:script>
        myLabel.text = "This is the text of my label.";
    </fx:script>
    

Note: for 1st method to work <?import java.lang.String?> needs to be imported.

like image 81
AlmasB Avatar answered Sep 19 '22 13:09

AlmasB