Is there any way of getting the Scene object of an FXML loaded file from the associated class controller.
I'm doing something like this:
@FXML
private AnchorPane anchor;
Scene scene = anchor.getScene();
but i'd like a solution that does not reference the AnchorPane control.
I tried your answer, but it did not work, I found the reason here:
JavaFX: How to get stage from controller during initialization?
after the comment:
don't use the static load method
but instead use instantiated loader's method
Why not? Controller is an abstract class, he's not aware about UI unless you deliberately make him know.
Nodes (inlcuding AnchorPane) are another story, they hardly exists outside for scenegraph. So it's perfectly fine to ask Node about his parent or scene.
If you still want to handle that separately there are next approaches:
you can create a custom controller and set scene after loader. Just note that at the time
initialize()
called it wouldn't yet initialized.You can create a custom fxml control which will incorporate controller and he can just call
getScene()
for itself. See an example here: https://stackoverflow.com/a/10718683/1054140