Search code examples
javafxcontrollerparentfxmlfxmlloader

How to get Stackpane from Main class in Controller class?


To familiarize myself with the scene builder I added a linechart and two numberaxis as nodes in a stackpane with the scene builder. The parent node will be loaded in the mainApp.java:

public class CsvCommander extends Application {    
    @Override
    public void start(Stage stage) throws Exception {        
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));           
        Scene scene = new Scene(root);        
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }   
}

Now, for further operations I want to get the stackpane of the parent in FXMLDocument.fxml, but I don't know how to...

e.g.

StackPane container = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml") or the like.

How can I get my root node or stackpane in the Controller pass?


Solution

  • Put an fx:id on the root element in the FXML file, and then inject it into the controller in the same way as other elements:

    FXML file:

    <!-- imports etc -->
    <StackPane xmlns="..." fx:controller="com.example.MyControllerClass" fx:id="container">
        <!-- nodes etc -->
    </StackPane>
    

    Controller:

    public class MyControllerClass {
    
        @FXML // will be initialized by FXMLLoader
        private StackPane container ;
    
        public void initialize() {
            // do something with container....
        }
    }