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

前端 未结 2 1790
野趣味
野趣味 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:11

    Here is one way to do this:

    ((VBox) root).getChildren().add(new Button("Java Button"));
    

    The snippet above assumes that the top container defined in your FXML is a VBox, if it is not a VBox, just cast it to whatever type you have chosen.

    I wonder how I can determine the type of the container at runtime, so I can write a more generic code.

    The type is likely a Pane, so casting to a Pane will work in most cases. Using a layout Pane as a Parent is usually recommended for most layout tasks in JavaFX.

提交回复
热议问题