FXML中的JavaScript脚本

时间:2015-07-21 10:11:52

标签: javafx javafx-8

我正在尝试从FXML reference运行以下示例:

这个例子包括在JavaScript脚本中声明一个String变量,然后在FXML中使用它与$运算符一起在标签中显示字符串。

问题在于,当我使用Java 8u40运行此示例时,Label为空而不是显示声明的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 个答案:

答案 0 :(得分:3)

似乎&#34; var myText&#34;不会在&#39; $&#39; <fx:define> <String fx:id="myText" fx:value="This is the text of my label." /> </fx:define> <Label text="$myText" /> &#39;范围内创建参考。执行查找。这可能不是你所寻找的答案,但是我相信为那些偶然发现同样问题的人提及替代方案是有用的,至少在这个问题得到解决或有人对这个问题有所了解之前。


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

  2. <?import java.lang.String?>
  3. 注意:需要导入第一种工作方法{{1}}。