簡體   English   中英

如何將變量從控制器代碼傳遞到fxml視圖?

[英]How to pass variable from controller code to fxml view?

我有幾個標簽和幾個textFields的自定義組件。 我需要實例化3次,但是每個版本都必須在所有標簽的前面加上不同的String。

我的組件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;

問題:如何將String從控制器代碼傳遞到fxml視圖,避免重復和不必要的工作?

您可以在FXML中使用綁定表達式從FXML名稱空間中獲取變量值。

在以下示例中,我們成功注入了名稱“ Foobar”。

foob​​ar的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM