Getting the global coordinate of a Node in JavaFX

这一生的挚爱 提交于 2020-01-12 14:24:07

问题


How can I get the actual position of a node in the scene. The absolute position, regardless of any containers/transforms.

For example, I want to translate a certain node a so that it would temporarily overlap another node b. So I wish to set his translateX property to b.globalX-a.globalX.

The documentation says:

Defines the X coordinate of the translation that is added to the transformed coordinates of this Node for the purpose of layout. Containers or Groups performing layout will set this variable relative to layoutBounds.minX in order to position the node at the desired layout location.

For example, if child should have a final location of finalX:

 child.layoutX = finalX - child.layoutBounds.minX;

That is, the final coordinates of any node should be

finalX = node.layoutX + node.layoutBounds.minX

However running the following code:

var rect;
Stage {
    title: "Application title"
    width: 250
    height:250
    scene: Scene {
        content: [
            Stack{content:[rect = Rectangle { width:10 height:10}] layoutX:10}
        ]
    }
}

println("finalX = {rect.layoutX+rect.layoutBounds.minX}");

gives me finalX = 0.0 instead of finalX = 10.0 as the docs seemingly state.

Is there a clear method to get the absolutely final positioning coordinates in JavaFX?


回答1:


For bounds:

bounds = rect.localToScene(rect.getBoundsInLocal());

Work for JavaFx 1 and 2.




回答2:


The only solution I found so far is

rect.localToScene(rect.layoutBounds.minX, rect.layoutBounds.minY) // a Point2D{x:Float y:Float} object

Which doesn't seem to me as the "best" way to do that (note that this function is not bound). Still it works for JavaFX 1.2.




回答3:


Since JavaFX 8, there are additional methods converting local coordinates to screen coordinates. Their names start with "localToScreen"

You can check following link http://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#localToScreen-double-double-



来源:https://stackoverflow.com/questions/1531538/getting-the-global-coordinate-of-a-node-in-javafx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!