FXML中的JavaScript脚本 [英] JavaScript script in a FXML

查看:51
本文介绍了FXML中的JavaScript脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

此示例包括在JavaScript脚本中声明String变量,然后稍后在FXML中将其与$运算符一起使用,以在Label中显示String.

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.

问题是,当我使用Java 8u40运行此示例时,Label为空而不是显示声明的String.

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

JavaFxComponent.java:

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:

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:

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

推荐答案

似乎"var myText"未在"$"执行查找的范围内创建引用.这可能不是您要找的答案,但是对于那些偶然发现同一问题的人,至少在解决此问题或有人对此事有所了解之前,我相信为他们提起替代方案会很有用.

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>
    

  • 注意:要使第一种方法起作用,必须导入<?import java.lang.String?>.

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

    这篇关于FXML中的JavaScript脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆