JavaFX - 如何将一个节点转换为另一个对象

3

很抱歉,我找不到解决方法。我必须将“Node”对象转换为“Line”对象。我的意思是这样的:
我有一个填充了许多节点的AnchorPane,其中一些是标签,大部分是线条。设置它们工作得很好,但是在我的代码中稍后我需要这些线条的坐标。我尝试过以下方法(下面有解释):

List<Line> lineList = new ArrayList<>();
    for (Node currentNode : anchorPaneGame.getChildren()){
        if (currentNode.getTypeSelector().equals("Line")){
            lineList.add(currentNode);
        }

我制作了一个列表,想要收集所有的线条,但这并没有起作用,因为(我引用一下我的IDE):“在列表中添加(javafx.scene.shape.Line)无法应用于(java.fx.scene.Node)”。
在此之前,我试图做以下操作:

Line tempLine = apGame.getChildren().get(apGame.getChildren().size()-1);  

当然,我得到了同样的错误(我知道最后一个元素是一条线,将其添加为最后一件事是硬编码的)。我做所有这些的原因是在最后执行 .getEndX() - 我尝试的第一件事是...
        AnchorPane.setLeftAnchor(borderPane, apGame.getChildren().get(apGame.getChildren().size()-1).getEndX());

这应该将Borderpane设置在AnchorPane apGame中找到的最后一行右侧。但是由于.getChildren仅返回节点,因此它不知道正在处理一条线,并且因此无法解决.getEndX()
您有任何想法如何使程序意识到给定的节点实际上是一条线吗?

1个回答

6

结合向下转型使用instanceof

List<Line> lineList = new ArrayList<>();
for (Node currentNode : anchorPaneGame.getChildren()){
    if (currentNode instanceof Line){
        lineList.add((Line)currentNode);
    }
}

谢谢,这正是我在寻找的!我知道一定有一种简单、聪明和巧妙的方法来做到这一点。 - harlekintiger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接