JavaFX multiple FXML and 1 shared controller


Question

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
4
7/28/2013 11:54:54 PM

Accepted Answer

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.

9
7/29/2013 1:32:24 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon