JavaFX - 如何从 AnchorPane 中删除特定节点

JavaFX - How to delete a specific Node from an AnchorPane

我正在使用 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.

在 JavaFX 中,节点可以简单地从 Parent (e.g. an AnchorPane) 中删除,使用 .getChildren() 然后 .remove(Object o)

参考

因此,如果您直接引用这些节点,则可以使用以下代码从 AnchorPane 中删除 Button

ap.getChildren().remove(btn);

查找

如果您出于某种原因没有对 Button btn 的引用,您可以使用 lookup(String selector) 来查找和删除它,如下所示:

ap.getChildren().remove(ap.lookup('.button'));

FXML

或者最后,由于您使用的是 SceneBuilder(因此使用 fxml),您还可以确保连接了一个控制器并为您的按钮分配一个 ID 以获取一个像这样引用并删除它:

// ... somewhere in your class
@FXML
private Button myButtonId;

// ... somewhere in a method
ap.getChildren().remove(myButtonId);