JavaFX : Adding a new node to Scene in java code when Scene is initially loaded from FXML

前端 未结 2 1814
野趣味
野趣味 2021-01-02 15:51

How can I add a new node to the Scene in java code when Scene is initially loaded from FXML ? I have loaded from FXML as shown below

Parent root = FXMLLoader         


        
2条回答
  •  孤独总比滥情好
    2021-01-02 16:07

    I do not know the reason behind your question. If what you want is to insert some nodes dynamically during the application or scene initialization, I suggest you use a initialize method at your controller.

    This method must be annotated with @FXML and have the following signature:

    void initialize()
    

    Then, you can inject the container where the button must be inserted on the controller and add the button to it:

    @FXML
    HBox buttonBox // assuming your button container is a HBox
    ...
    
    @FXML
    protected void initialize() {
        buttonBox.getChildren().add(new Button("Click me!"));
    }
    

    The method initialize is called after the components defined at the FXML file were built.

提交回复
热议问题