javafx FXML and Controllers Passing data to FXML - Specifying the controller instance


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


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.


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

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

<VBox xmlns:fx="">
        <Text fx:id="target" />


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

public class TestController {

    private final String data;

    public TestController(String data) { = data;
    private Text target;
    public void initialize() {
        // handle data once the fields are injected


Code used for loading the fxml

String data = "Hello World!";

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

TestController controller = new TestController(data);

Parent root = loader.load();