在 JavaFX 中获取节点的真实位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31148690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:42:57  来源:igfitidea点击:

Get real position of a node in JavaFX

javajavafxjavafx-2javafx-8

提问by maryam

What is the best way to get the absolute position of a node in JavaFX?

在 JavaFX 中获取节点绝对位置的最佳方法是什么?

Imagine we have a node in a Pane (Hbox, Stackpane, or any other pane) and that may have a parent itself.

想象一下,我们在窗格(Hbox、Stackpane 或任何其他窗格)中有一个节点,并且它本身可能有一个父节点。

I want to get the absolute position of that node and use it in another pane.

我想获取该节点的绝对位置并在另一个窗格中使用它。

采纳答案by James_D

It depends a little what you mean by "absolute". There is a coordinate system for the node, a coordinate system for its parent, one for its parent, and so on, and eventually a coordinate system for the Sceneand one for the screen (which is potentially a collection of physical display devices).

这取决于你所说的“绝对”是什么意思。节点有一个坐标系,其父级有一个坐标系,父级有一个坐标系,依此类推,最终有一个坐标系用于Scene屏幕(可能是物理显示设备的集合)。

You probably either want the coordinates relative to the Scene, in which case you could do

您可能想要相对于 的坐标Scene,在这种情况下,您可以这样做

Bounds boundsInScene = node.localToScene(node.getBoundsInLocal());

or the coordinates relative to the screen:

或相对于屏幕的坐标:

Bounds boundsInScreen = node.localToScreen(node.getBoundsInLocal());

In either case the resulting Boundsobject has getMinX(), getMinY(), getMaxX(), getMaxY(), getWidth()and getHeight()methods.

在任一种情况下,所得Bounds物体具有getMinX()getMinY()getMaxX()getMaxY()getWidth()getHeight()方法。

回答by Ragib

Assuming the name of the main Stage "window",and the name of the node "menu" you can do this :-)

假设主舞台的名称“窗口”和节点“菜单”的名称,您可以这样做:-)

double X=Main.window.getX()+menu.getLayoutX();
double Y=Main.window.getY()+menu.getLayoutY();

回答by Giovanni Contreras

if you want to translate local coordinates to scenne coords you can use localToScene method .

如果要将本地坐标转换为场景坐标,可以使用 localToScene 方法。

 Point2D point2D = node.localToScene(0,0);

for example if you want to know the center of a pane but in scene coordinates

例如,如果您想知道窗格的中心但在场景坐标中

Point2D point2D = pane.localToScene(pane.getWidth()/2,pane.getHeight()/2);