Leaking 'this' in constructor when using <fx: root>
Introduction to FXML provides an example of creating custom components using <fx: root>. Here is a snippet of 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's the 'this' leak constructor, which can cause some frustration .
Is it safe to pass 'this' to FXMLLoader in the constructor? If not, any suggestion to make this code safe?
source to share
Given the example from docs.oracle.com and the fact that they are using it to demonstrate a feature, I would say it should be safe. However, you are making a good point.
What you can do is try to avoid classes that are both root and controller at the same time. After all, semantically, it would be better to have them separately. So in the above example you can have CustomBox extends VBox
for fx:root
and CustomBoxController
how fx:controller
and instead put initialization load instead of .fxml.
I suppose that at least you can have some sort of wrapper around such a combined custom control. The shell then created the control object, initialized the loader, and finally loaded it. If you have more than one such class, you can use the same wrapper to initialize all of your custom controls.
source to share