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);
    }
}

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.


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

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

    链接地址: http://www.djcxy.com/p/27594.html

    上一篇: 在我的中启用mysqli

    下一篇: FXML中的JavaScript脚本