对不起,我找不到解决这个问题的方法。我必须让一个“节点”对象成为一个“线”对象。我的意思是:
我有一个 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()
.
你有什么想法可以让程序意识到给定的节点实际上是一条线吗?
最佳答案
将 instanceof
与向下转型结合使用:
List<Line> lineList = new ArrayList<>();
for (Node currentNode : anchorPaneGame.getChildren()){
if (currentNode instanceof Line){
lineList.add((Line)currentNode);
}
}
关于javafx - 如何将节点转换为另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825300/