首页 > 解决方案 > 有没有办法在控制器中初始化一个变量,并在 FXML 中使用它?

问题描述

所以,我在 FXML 中制作了一个菜单,并且我使用了一个 Group,所以我必须设置一个 prefWidth 否则它看起来很奇怪。为此,我想在控制器中使用屏幕宽度初始化一个变量,然后在 FXML 中设置菜单时使用宽度变量。但我就是找不到办法做到这一点。

概括这个问题,我想在控制器中初始化一个变量,然后在 FXML 中使用它,如下所示:

[控制器]

package sample;

import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
    @Override
    public void initialize (URL url, ResourceBundle resourceBundle) {
        String text = "test";
    }
}

[FXML]

<?import javafx.scene.control.Label?>
<?import javafx.scene.BorderPane?>

<BorderPane>
    <center>
        <label text="<!--use var 'text' here-->"/>
    </center>
</BorderPane>

我知道,还有其他方法可以做到这一点(比如 id-ing 并在控制器中设置文本),但我只是想看看是否可以这样做。

标签: javajavafxfxml

解决方案


使用属性代替变量。将其放在班级级别。

public class Controller implements Initializable {

    private String text; // or use binding property

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        text = "hello";
    }
}

FXML

<BorderPane fx:controller="sample.Controller"
            xmlns:fx="http://javafx.com/fxml">

    <center>
        <Label text="${controller.text}"/>

    </center>
</BorderPane>

推荐阅读