获取具有一些空区域的边框窗格中节点的绝对坐标



我有一组定制的"按钮",用于我的游戏菜单屏幕。它基本上是一个堆叠了Rectangle节点和Text节点的StackPane。基本上,这类似于我的按钮的结构。

Pane button1 = new StackPane(new Rectangle(100, 50), new Text("Play!"));
Pane button2 = [....];

然后我将按钮插入 VBox 并插入我的菜单中,并带有标题文本:

VBox buttons = new VBox(button1, button2, button3...);
Pane menuScreen = new BorderPane(buttons, new Text("The Game"), null, null, null);

但是,对于与按钮相比的鼠标位置的自定义检测,我需要知道按钮的位置......

int x = button1.getLayoutX(); //returns 0
int x = button1.getTranslateX(); //returns 0
int x = button1.localToScene(0, 0).getX(); //returns 0
int x = button1.localToScene(buttons.get(0).getBoundsInLocal()).getMinX(); //returns 0
int x = button1.localToScene(buttons.get(0).getBoundsInLocal()).getMaxX(); //returns the width of the entire scene
int x = buttons.get(0).getTranslateX(); //returns 0
int y = button1.localToScene(buttons.get(0).getBoundsInLocal()).getMinY(); 

如果我将 VBox 设置为 .setAlignment(Pos.CENTER),则最后一种情况返回 234.0,如果没有,则返回 64.0。但对于.getMinX(),无论哪种情况,它都保持在 0.0。我相信这与BorderPane的左/右/机器人区域设置为null而顶部区域具有标题文本有关。

当按钮位于布局窗格中而不是Pane类本身时,我找不到任何获取x坐标的方法。我也尝试了StackPane。我的怀疑是没有固定的坐标并且涉及属性,但是当我不知道我在寻找什么时,我只会因为阅读它而感到困惑。

我已经尝试了这个问题的解决方案,这似乎是一样的,但正如我提到的,恐怕我的minX()没有设定的值,因为VBox是唯一填满我BorderPane中心行的东西。

编辑:当我使用 .setAlignment(Pos.CENTER) 时,StackPane 似乎为 .getMinX() 提供了正确的值,但我不允许对文本执行此操作,只能使用 VBox,因此文本卡在按钮顶部。

我的问题是由 VBox 和我的 StackPanes 占用所有可能的空间引起的,而不仅仅是可见矩形的区域。通过在包含矩形和文本的 StackPane 上调用 setMaxWidth(100) 解决了问题。

此外,唯一的问题似乎是您的 x 坐标为零。也许这是"真实的"。在 button1 上设置背景以查看它在布局中的位置。– James_D

最新更新