JavaFX multiple FXML and 1 shared controller

后端 未结 1 483
清歌不尽
清歌不尽 2020-12-06 08:18

I have created a root FXML which is a BorderPane and it has his own root controller. I want to dynamicly add FXML\'s to the center of this borderpane.

Each of these

相关标签:
1条回答
  • 2020-12-06 08:57

    Background

    I don't know that sharing a controller instance is really recommended, at least I've never seen it done before.

    Even if you set the controller class in each of the fxml's you are loading to the same value, it isn't going to share the same controller instance, because every time you load a controller, it will create a new instance (object) of the controller class (which doesn't seem to be what you want).

    Potential Solutions

    I haven't tried either of these solutions, but believe they will work.

    The initialize method will probably be called each time you load a new fxml file. So you will want to account for that in your logic by making initialize idempotent.

    A. Manually set the controller instance.

    1. Remove all of the references to your controller class from your fxml files.
    2. Manually create an instance of your controller class.

      MyController controller = new MyController(); 
      
    3. Set the controller to your controller instance before you load each fxml.

      FXMLLoader loader = new FXMLLoader();
      loader.setController(controller);
      Panel panel = (Panel) loader.load("myfxml.fxml");
      
    4. Repeat step 3 for each of your fxml files, using the same controller reference each time.

    B. Use a controller factory.

    You can set a controller factory on your fxml loaders and have the controller factory always return the same controller instance.

    0 讨论(0)
提交回复
热议问题