javajavafx-8fxmlfxmlloader

Passing fxml objects between two seperate controller classes javafx fxml


I have two seperate stages (mainStage, popupStage), both with their own controller class and associated fxml file.

I would like to access some buttons defined with the @FXML annotation in mainStage's controller, from popupStage's controller. I've found that using loader.getController() to create an instance of the controller that has all the fxml button objects, then passing it to the popupScene's controller, and simply calling mainStageControllerInstance.reset(); from the popupStage controller would be a viable solution. I've managed to create a mainStageController instance using this approach, however, the buttons retrieved from this instance weren't the same ones that were being displayed on the mainStage at runtime. Therefore I am only able to affect the buttons from the mainStage controller class, and not by calling the @FXML reset() method from the popupStage controller, and adding the buttons retrieved from the loader.getController() object.

Creating the mainStageControllerInstance object:

FXMLLoader loader = new FXMLLoader(getClass().getResource("main_scene.fxml"));
AnchorPane root = loader.load();
mainStageController mainStageControllerInstance  = loader.getController();

I've tried adding this code to multiple different classes/methods of the program in hopes that I would be able to reference the buttons displayed on mainStage, and modify them by the click of a button on the popup, but nothing seemed to work.

I have checked all related questions that I came accross that seemingly answered my question, but nothing worked. I'd greatly appreciate any help with this issue.


Solution

  • For the sake of anyone who comes across this post in the future, this is how I managed to solve the issue:

    The following method creates mainStage's scene using the fxml file as root.

    public Scene getMainStageScene() throws Exception {
        
        Parent root = FXMLLoader.load(getClass().getResource("main_stage.fxml"));    
        Scene mainStageScene = new Scene(root, 800, 800);
        
    return mainStageScene; 
    

    }

    To obtain the object that has access to all elements injected by FXML, I modified the code above the following way:

    public Scene getMainStageScene() throws Exception {
        
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("main_stage.fxml"));
        Parent root = loader.load();
    
    //defined as: public static mainStage mainStageControllerInstance; before this method
        mainStageControllerInstance = loader.getController(); 
    
        Scene mainStageScene = new Scene(root, 800, 800);
        
    return mainStageScene;   
    

    }

    And now I am able to access/modify the objects displayed on mainStage from everywhere in the program, including the popup window.