javafx Passing data to FXML - Specifying the controller instance


Example

Problem: Some data needs to be passed to a scene loaded from a fxml.

Solution

Set the controller using the FXMLLoader instance used later to load the fxml.

Make sure the controller contains the relevant data before loading the fxml.

Note: in this case the fxml file must not contain the fx:controller attribute.

FXML

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

<?import javafx.scene.text.*?>
<?import javafx.scene.layout.*?>

<VBox xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <Text fx:id="target" />
    </children>
</VBox>

Controller

import javafx.fxml.FXML;
import javafx.scene.text.Text;

public class TestController {

    private final String data;

    public TestController(String data) {
        this.data = data;
    }
    
    @FXML
    private Text target;
    
    public void initialize() {
        // handle data once the fields are injected
        target.setText(data);
    }

}

Code used for loading the fxml

String data = "Hello World!";

FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));

TestController controller = new TestController(data);
loader.setController(controller);

Parent root = loader.load();