Search code examples
javajavafxcontrollerinitialization

How to run a function everytime the app switches to the scene in JavaFX?


I want to use a function that can run every time a scene is loaded. Initialize doesn't work because it only runs when I first go on the scene and does not run again after that. This is the initialize function that I have.

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    initStore();

    backBtn.setOnAction(e -> {
        Stage stage = (Stage) ((Node) e.getSource()).getScene().getWindow();
        stage.hide();
        stage.setScene(Application.homeScene);
        stage.setMaximized(true);
        stage.show();
    });
}

I tried using stage.setOnHidden(e -> { ... }) on the main class but I can't figure out how to move my function to another file. Is there a function that runs everytime the scene and controller loads?


Solution

  • scene is a property of a window.

    You can add a change listener to the scene property and it will invoke the listener any time the property changes.

    stage.sceneProperty().addListener((observable, oldValue, newValue) -> {
        // code to run on scene change.
    });
    

    If you have multiple stages, each stage has its own scene property. If you wanted to listen to scene changes for each stage, you would need to add listeners to the scene properties for each stage.

    Whether this information will actually assist in solving the core task you are trying to perform, I do not know. You may be asking an xy problem, or maybe not.