JavaFX - 如何从 AnchorPane 中删除特定节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30018663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX - How to delete a specific Node from an AnchorPane
提问by Calips
I'm using SceneBuilder 8.0.0 and JavaFX 8.
I have a Button btn
and a Label lbl
attached to an AnchorPane ap
.
When the application starts, btn
and lbl
are attached to ap
.
我正在使用 SceneBuilder 8.0.0 和 JavaFX 8。
我有一个Button btn
和一个Label lbl
附加到AnchorPane ap
.
当应用程序启动,btn
并lbl
连接到ap
。
How can i delete one of these nodes ?(i only know clear() method which deletes all the nodes from
ap
). thanks.
如何删除这些节点之一?(我只知道从 中删除所有节点的 clear() 方法
ap
)。谢谢。
采纳答案by Mike Rombout
In JavaFX, nodes can simply be removed from a Parent(e.g. an AnchorPane) using .getChildren()
following by .remove(Object o)
在 JavaFX 中,可以使用以下方法简单地从父节点(例如AnchorPane)中删除节点.getChildren()
.remove(Object o)
Reference
参考
So if you have a direct reference to these Nodes, you could use the following code to remove the Button
from the AnchorPane
:
所以,如果你有一个直接引用这些节点,你可以使用下面的代码删除Button
来自AnchorPane
:
ap.getChildren().remove(btn);
Lookup
抬头
If you, for some reason, don't have a reference to the Button btn
you can use lookup(String selector)to find and remove it like so:
如果您由于某种原因没有引用Button btn
您可以使用lookup(String selector)来查找和删除它,如下所示:
ap.getChildren().remove(ap.lookup('.button'));
FXML
文件格式
Or finally, since you are using SceneBuilder (and thus fxml) you could also make sure you hava a Controller connectedand assign an id to your Button to get ahold of a reference and remove it like so:
或者最后,由于您使用的是 SceneBuilder(以及 fxml),您还可以确保连接了一个 Controller并为您的 Button 分配一个 id 以获取引用并像这样删除它:
// ... somewhere in your class
@FXML
private Button myButtonId;
// ... somewhere in a method
ap.getChildren().remove(myButtonId);