Michał Mielec
Michał Mielec

Reputation: 1651

How to pass variable from controller code to fxml view?

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?

Upvotes: 3

Views: 2510

Answers (1)

jewelsea
jewelsea

Reputation: 159341

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".

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

Upvotes: 4

Related Questions