3

Introduction to FXML has example how to build custom components with <fx:root>. Here is some snippet from the document:

public CustomControl() {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("custom_control.fxml"));
    fxmlLoader.setRoot(this);
    fxmlLoader.setController(this);

    try {
        fxmlLoader.load();
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    }
}

Here, the constructor is leaking 'this' that might cause some unpleasure consequence.

Is it safe to pass 'this' to FXMLLoader in constructor? If not, any suggestion to make this code safe?

Community
  • 1
  • 1
Venusaur
  • 191
  • 12
  • I am running into this issue now, on a class i didn't realize had it (since i don't really use it for now), and checked the class i do use, and realized i had put the above code in an `init()` method, and that worked for me. i'm not sure if this actually solves anything, but warnings are gone. – XaolingBao Jul 03 '16 at 20:15

1 Answers1

1

Considering the example is from docs.oracle.com and the fact that they use it to demonstrate a feature, I'd say it should be safe. Nevertheless, you make a good point.

What you can do is try and avoid classes which represent both the root and the controller at the same time. After all semantically it would be nicer to have them separate. So in the example above you could have CustomBox extends VBox for fx:root and CustomBoxController as fx:controller and put the initialization burden on .fxml instead.

I suppose at the very least you could have some sort of wrapper around such a combined custom control. The wrapper would then create the control object, initiliaze the loader with it and finally load it. If you have more than 1 such class you could use the same wrapper to initialize all your custom controls.

AlmasB
  • 3,377
  • 2
  • 15
  • 17