parent 节点丢失 child
parent node losing its child
我在处理某些 java fx 组件时观察到一些奇怪的行为。一旦在 GUI 上按下按钮,我试图通过控制器将 children 动态添加到 parent 节点。这是问题的可重现场景:
VBox vbox = new VBox();
HBox entry = new HBox();
Button button = new Button();
TextField text = new TextField();
entry.getChildren().add(text);
entry.getChildren().add(button);
vbox.getChildren().add(entry);
System.out.println(vbox.getChildren().isEmpty() ? "empty" : "not empty"); //prints out "not empty"
HBox newEntry = new HBox(entry);
System.out.println(vbox.getChildren().isEmpty() ? "empty" : "not empty"); //prints out "empty"
你能告诉我为什么当我将 entry
传递给构造函数时 vbox
作为 child 丢失 entry
吗?我将 entry
传递给构造函数,以便复制已通过 FXML 表单设置的所有其他 object attributes/properties。在我的实际代码中,每个元素都有一个不同的标识符,通过 node.setId()
方法设置,所以重复的 ID 不是问题。我不知道一些潜在的机制吗?谢谢你。
I am passing entry
to the constructor in order to copy all the other object attributes/properties that are already set via the FXML form.
这样不行。该构造函数添加与新创建的 HBox
的 child 相同的实例。由于 Node
只能有一个 parent 并且 Node
出现在 Parent
的 child 列表中,因此 JavaFX 必须通过删除Node
来自其前 parent 的 child 列表。
请注意,相当多的 Pane
允许您将 children 传递给构造函数之一。这些是 不是 复制构造函数,只是 "shortcuts" 允许您添加 children 而无需使用 pane.getChildren().addAll(children);
实际上我不知道JavaFX API.
中 Node
s 的任何复制构造函数
HBox newEntry = new HBox(entry);
创建一个包含 entry
的新 HBox
,因为它只有 child。
与其尝试复制场景图的一部分,通常更容易创建一个辅助方法来创建场景图的一部分(也可以使用 fxml 文件完成)。
(JavaFX API 中没有允许您创建 Node
层次结构副本的功能。)
我在处理某些 java fx 组件时观察到一些奇怪的行为。一旦在 GUI 上按下按钮,我试图通过控制器将 children 动态添加到 parent 节点。这是问题的可重现场景:
VBox vbox = new VBox();
HBox entry = new HBox();
Button button = new Button();
TextField text = new TextField();
entry.getChildren().add(text);
entry.getChildren().add(button);
vbox.getChildren().add(entry);
System.out.println(vbox.getChildren().isEmpty() ? "empty" : "not empty"); //prints out "not empty"
HBox newEntry = new HBox(entry);
System.out.println(vbox.getChildren().isEmpty() ? "empty" : "not empty"); //prints out "empty"
你能告诉我为什么当我将 entry
传递给构造函数时 vbox
作为 child 丢失 entry
吗?我将 entry
传递给构造函数,以便复制已通过 FXML 表单设置的所有其他 object attributes/properties。在我的实际代码中,每个元素都有一个不同的标识符,通过 node.setId()
方法设置,所以重复的 ID 不是问题。我不知道一些潜在的机制吗?谢谢你。
I am passing
entry
to the constructor in order to copy all the other object attributes/properties that are already set via the FXML form.
这样不行。该构造函数添加与新创建的 HBox
的 child 相同的实例。由于 Node
只能有一个 parent 并且 Node
出现在 Parent
的 child 列表中,因此 JavaFX 必须通过删除Node
来自其前 parent 的 child 列表。
请注意,相当多的 Pane
允许您将 children 传递给构造函数之一。这些是 不是 复制构造函数,只是 "shortcuts" 允许您添加 children 而无需使用 pane.getChildren().addAll(children);
实际上我不知道JavaFX API.
Node
s 的任何复制构造函数
HBox newEntry = new HBox(entry);
创建一个包含 entry
的新 HBox
,因为它只有 child。
与其尝试复制场景图的一部分,通常更容易创建一个辅助方法来创建场景图的一部分(也可以使用 fxml 文件完成)。
(JavaFX API 中没有允许您创建 Node
层次结构副本的功能。)