JavaFX:最初从FXML加载Scene时,将新节点添加到Java代码中的Scene中 [英] JavaFX : Adding a new node to Scene in java code when Scene is initially loaded from FXML

查看:161
本文介绍了JavaFX:最初从FXML加载Scene时,将新节点添加到Java代码中的Scene中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当最初从FXML加载Scene时,如何在Java代码中为Scene添加一个新节点? 我已经从FXML加载,如下所示

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.load(getClass().getResource("sample.fxml"));

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

例如,现在说如何在Java代码中向场景添加按钮?

Now say for example how do I add button to the scene in Java code?

推荐答案

我不知道您的问题背后的原因.如果要在应用程序或场景初始化期间动态插入一些节点,建议您使用

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.

此方法必须用@FXML注释并具有以下签名:

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!"));
}

在构建FXML文件定义的组件之后,将调用方法initialize.

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

这篇关于JavaFX:最初从FXML加载Scene时,将新节点添加到Java代码中的Scene中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆