javafx FXML and Controllers Passing parameters to FXML - using a controllerFactory


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


Specify a controller factory that is responsible for creating the controllers. Pass the data to the controller instance created by the factory.


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

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

<VBox xmlns:fx="" fx:controller="valuepassing.TestController">
        <Text fx:id="target" />


package valuepassing;

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!";

Map<Class, Callable<?>> creators = new HashMap<>();
creators.put(TestController.class, new Callable<TestController>() {

    public TestController call() throws Exception {
        return new TestController(data);


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

loader.setControllerFactory(new Callback<Class<?>, Object>() {

    public Object call(Class<?> param) {
        Callable<?> callable = creators.get(param);
        if (callable == null) {
            try {
                // default handling: use no-arg constructor
                return param.newInstance();
            } catch (InstantiationException | IllegalAccessException ex) {
                throw new IllegalStateException(ex);
        } else {
            try {
            } catch (Exception ex) {
                throw new IllegalStateException(ex);

Parent root = loader.load();

This may seem complex, but it can be useful, if the fxml should be able to decide, which controller class it needs.