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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:59:33  来源:igfitidea点击:

JavaFX - How to delete a specific Node from an AnchorPane

javajavafxjavafx-8

提问by Calips

I'm using SceneBuilder 8.0.0 and JavaFX 8.
I have a Button btnand a Label lblattached to an AnchorPane ap.
When the application starts, btnand lblare attached to ap.

我正在使用 SceneBuilder 8.0.0 和 JavaFX 8。
我有一个Button btn和一个Label lbl附加到AnchorPane ap.
当应用程序启动,btnlbl连接到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 Buttonfrom the AnchorPane:

所以,如果你有一个直接引用这些节点,你可以使用下面的代码删除Button来自AnchorPane

ap.getChildren().remove(btn);

Lookup

抬头

If you, for some reason, don't have a reference to the Button btnyou 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);