如何将变量从控制器代码传递到 fxml 视图?

How to pass variable from controller code to fxml view?

我有一些标签和文本字段很少的自定义组件。我需要实例化它3次,但每个版本必须所有标签都以不同的字符串为前缀。

我的组件 fxml 的片段:

<Label text="inclusions type:"/>
<Label text="inclusions size:" GridPane.rowIndex="1"/>
<Label text="inclusions number:" GridPane.rowIndex="2"/>

我想实现某种代码占位符,例如:

<Label text="$variable inclusions type:"/>
<Label text="$variable size:" GridPane.rowIndex="1"/>
<Label text="$variable number:" GridPane.rowIndex="2"/>

我尽量避免一个一个地注入所有标签,因为我知道不可能像 ex 那样一次将所有标签注入控制器。 Collection<Label> allLabels;

问题:如何将字符串从控制器代码传递到 fxml 视图,避免重复和不必要的工作?

您可以在 FXML 中使用 binding expression 从 FXML 命名空间中获取变量值。

在下面的例子中,我们成功注入了名字"Foobar".

inclusions.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>

<VBox spacing="10" xmlns:fx="http://javafx.com/fxml">
  <Label text="${name + ' inclusions type'}"/>
  <Label text="${name + ' inclusions size'}"/>
  <Label text="${name + ' inclusions number'}"/>
</VBox>

NamespaceAware.java

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class NamespaceAware extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader();
        loader.getNamespace().put("name", "Foobar");
        loader.setLocation(getClass().getResource("inclusions.fxml"));
        Pane content = loader.load();

        content.setPadding(new Insets(10));

        stage.setScene(new Scene(content));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}