How to pass variable from controller code to fxml view?

大憨熊 提交于 2019-12-10 10:47:03

问题


I have custom component with few labels and few textFields. I need to instantiate it 3 times, but each version must have all labels prefixed with different String.

Fragment of my component fxml:

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

I would like to achieve some kind of code placeholder like:

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

I try to avoid injecting all labels one by one, as I know there is no possibility to inject all labels at once to controller like ex. Collection<Label> allLabels;

Question: How to pass String from controller code to fxml view, avoiding duplication and unnecessary work?


回答1:


You can use a binding expression in your FXML to grab variable values out of the FXML namespace.

In the following example, we successfully inject the name "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);
    }
}


来源:https://stackoverflow.com/questions/40940750/how-to-pass-variable-from-controller-code-to-fxml-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!