I have two main screens in my application build with FXML ( loginWindow and mainWindow ). User can
- login from loginWindow to mainWindow
- logout from mainWindow to loginWindow
Right now I'm using this method to change scene via fxml file
private Initializable replaceSceneContent(String fxml) throws Exception {
    FXMLLoader loader = new FXMLLoader();
    InputStream in = WRMS.class.getResourceAsStream(fxml);
    loader.setBuilderFactory(new JavaFXBuilderFactory());
    loader.setLocation(WRMS.class.getResource(fxml));
    AnchorPane page;
    try {
        page = (AnchorPane) loader.load(in);
    } finally {
        in.close();
    }
    Scene scene = new Scene(page);
    mainStage.setScene(scene);
    mainStage.sizeToScene();
    return (Initializable) loader.getController();
}
And this methods to switch to login and main window:
private void gotoMain() {        
try {                
    MainController mainController = (MainController) replaceSceneContent("Main.fxml");                
    mainController.setApp(this);
} catch (Exception ex) {
    ex.printStackTrace();                
}
}
private void gotoLogin() {        
try {
    LoginController login = (LoginController) replaceSceneContent("Login.fxml");
login.setApp(this);
} catch (Exception ex) {
    log.error(WRMS.class.getName() + ex);
}
}
It is working fine. Only one problem is that my method replaceSceneContent every time it is called is creating new instance of controller. I would like to have only one instance of each controller and switch between them. Is it possible? If yes, how to use FXML loader in this case?
 
     
     
    