我可以在不知道其父节点的情况下从场景图中删除一个节点
吗?
换句话说,我可以做这样的事情吗?
@FXML private ToolBar toolBar;
@FXML
protected void handleCloseButtonAction(ActionEvent actionEvent) {
toolBar.getParent().getChildrenUnmodifiable().remove(toolBar);
actionEvent.consume();
}
如果我这样做,它会抛出一个 java.lang.UnsupportedOperationException
。
最佳答案
你得到了 UnsupportedOperationException ,因为 Parent#getChildrenUnmodifiable
返回一个只读列表:
Gets the list of children of this Parent as a read-only list.
如果你存储父容器的引用总是更好更安全,但理论上你可以通过(向下)转换 Parent
来做到这一点getParent()
返回的对象父容器类型的方法。
例如,如果 ToolBar
添加到 VBox
:
((VBox) toolBar.getParent()).getChildren().remove(toolBar);
或者,如果你想更通用一点,你可以将返回的父级转换为 Pane
在类型检查之后,因为这个类是 JavaFX 容器的父类(super class),它允许修改子列表:
if (toolBar.getParent() instanceof Pane)
((Pane) toolBar.getParent()).getChildren().remove(toolBar);
不过,我还是建议存储父容器的引用,而不是遵循这些(或类似)方法之一,因为这不是一个干净的方法,而且由于向下转换不是一个安全的解决方案(没有类型检查)。
关于java - 在不知道父节点的情况下删除节点 (JavaFX),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38393914/