9

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.

nailujed
  • 1,169
  • 5
  • 17
  • 23

2 Answers2

13

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:

  1. you can create a custom controller and set scene after loader. Just note that at the time initialize() called it wouldn't yet initialized.

    public class MyController {
        private void Scene scene;
        public void setScene(Scene scene) { this.scene = scene; }
    
    }
    
    // loading code
    FXMLLoader fxmlLoader = new FXMLLoader();
    AnchorPane root = (AnchorPane) fxmlLoader.load(getClass().getResource("MyApp.fxml"));
    MyController myController = (MyController) fxmlLoader.getController();
    myController.setScene(scene);
    
  2. 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

Community
  • 1
  • 1
Sergey Grinev
  • 34,078
  • 10
  • 128
  • 141
3

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:

// loading code 

don't use the static load method

AnchorPane root=(AnchorPane) FXMLLoader.load(getClass().getResource("MyApp.fxml"));

but instead use instantiated loader's method

AnchorPane root=(AnchorPane) fxmlLoaded.load(getClass().getResource("MyApp.fxml"));
Community
  • 1
  • 1
kernel255
  • 41
  • 2
  • How is this different to the answer already posted? That answer was using the instance method, not a static load method. – Aaron D Aug 19 '15 at 14:22
  • 1
    @AaronD, I edited the accepted answer to correct it, for the sake of future users who will read it. Most likely it was a typo while posting the answer. – Uluk Biy Aug 19 '15 at 14:23
  • oh thanks, although u missed one entry of fxmlLoader, I fixed that. – Sergey Grinev Aug 19 '15 at 19:29