JavaFX multiple FXML and 1 shared controller

与世无争的帅哥 提交于 2019-11-27 19:11:20

问题


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 fxml's share the same controller, root controller. I have done this in netbeans by choosing an exsisting controller when creating an empty FXML file.

I also have gave the nodes different id names, but the root controller does not recognize the nodes in these fxml's.

Is it possible to share the same controller for different fxml's?

Thanks in advance


回答1:


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.



来源:https://stackoverflow.com/questions/17914254/javafx-multiple-fxml-and-1-shared-controller

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