How to switch javafx application controller without reloading FXML file?

我怕爱的太早我们不能终老 提交于 2019-12-08 11:58:07

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/20919691/how-to-switch-javafx-application-controller-without-reloading-fxml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!