2016-12-02 31 views
1

我有幾個標籤和幾個textFields的自定義組件。我需要實例化它3次,但每個版本都必須具有以不同字符串作爲前綴的所有標籤。如何將變量從控制器代碼傳遞給fxml視圖?

片段我的組件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"/> 

我會盡量避免注射的所有標籤一個接一個,因爲我知道沒有可能一次將所有標籤注入控制器,如前。 Collection<Label> allLabels;

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

+1

如果要動態地添加組件,您應該實例,並將其在Java代碼中添加場景! Fxml用於手動定義靜態組件。在Fxml文件中使用動態組件毫無意義。 – Omid

+0

我明白,但將.fxml文件和「Swing style」代碼放在一起對我來說並不好。但我有些迂腐:D –

+1

我想我誤解了。如果你想注入標籤的文本的一部分,而不是許多帶有一些可變文本的標籤,這是有道理的! – Omid

回答

2

您可以在FXML中使用binding expression從FXML名稱空間中獲取變量值。

在下面的例子中,我們成功地注入名稱「Foobar」。

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

我試過這個,但我沒有弄清楚單引號,FxmlLoader向我拋出異常。謝謝!!! –

+0

看來場景構建器(都來自Oracle和Gluon)不支持連接。 –

+1

是的,這是你必須採取與膠粘劑。我不知道你會怎麼做。奇怪的是,他們的支持頁面鏈接到StackOverflow,我沒有看到他們的支持頁面中的問題跟蹤鏈接。也許如果你只是標記了膠子的問題或者他們可能會研究的問題。膠子也提供商業支持,並在他們的網頁上有一個鏈接要求,這是一條可能的路線。 Intellij想法檢查也不能正確解析表達式。因此,功能請求也可以針對Intellij提出。 – jewelsea

相關問題