0

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?

Dmitry
  • 6,716
  • 14
  • 37
  • 39
kingkong
  • 1,537
  • 6
  • 27
  • 48

1 Answers1

0

You can create a controller instance and then set the controller into the loader.

You could get the controller using a singleton pattern if you wanted only a single instance of the controller for an application.

Sample code from Passing Parameters JavaFX FXML

CustomerDialogController dialogController = 
    new CustomerDialogController(param1, param2);

FXMLLoader loader = new FXMLLoader(
    getClass().getResource(
        "customerDialog.fxml"
    )
);
loader.setController(dialogController);

Pane mainPane = (Pane) loader.load();
Community
  • 1
  • 1
jewelsea
  • 150,031
  • 14
  • 366
  • 406