JavaScript script in a FXML

我是研究僧i 提交于 2019-12-10 12:57:18

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/31536169/javascript-script-in-a-fxml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!