Javafx-2 – JavaFX: when the scene is initially loaded from fxml, a new node is added to the scene in the Java code

When a scene is initially loaded from F XML, how do I add a new node to the scene in Java code?

Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

Scene scene = new Scene(root,1000,600,Color.DODGERBLUE);

Now, for example, how do I add buttons to the scene in Java code?

Solution

I don't know the reason behind your problem If you want to dynamically insert some nodes during application or scenario initialization, I recommend that you use the initialize method on the controller

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

void initialize()

You can then inject the container into which the button must be inserted on the controller and add the button to the controller:

@FXML
H@R_542_2419@ button@R_542_2419@ // assuming your button container is a H@R_542_2419@
...

@FXML
protected void initialize() {
    button@R_542_2419@.getChildren().add(new Button("Click me!"));
}

The method initialization is called after constructing the components defined in the FXML file.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>