Get real position of a node in JavaFX
Asked Answered
C

3

20

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

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

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

Curable answered 30/6, 2015 at 21:18 Comment(0)
D
57

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 Scene and one for the screen (which is potentially a collection of physical display devices).

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

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

or the coordinates relative to the screen:

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

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

Dusty answered 30/6, 2015 at 23:6 Comment(6)
Out of curiosity, do you have any idea why they didn't make a getCenterX() and getCenterY() method?Lenorelenox
@Lenorelenox No, not really, but there's always a balance between overspecifying an API and providing enough functionality. My guess (it's a guess) is that the most important use case for bounds is for layout, and I can imagine that minX, minY, width and height would be the most important properties in that use case, with maxX and maxY the next most useful. centerX and centerY probably don't have enough justification when it is already easy enough to compute them from the others.Dusty
@Dusty ...It sometimes doesn't work!Why ? I don't understand really!Curable
@Curable When doesn't it work? What happens when it doesn't work? You should probably post a new question that has a complete, simple example showing it failing to do what you expect. Do you understand how it works? If not, did you read the API docs for the classes and methods involved?Dusty
@SedrickJefferson Sorry, I don't understand what you mean by that.Dusty
@Lenorelenox JavaFX11 added getCenterX() etc. methods.Cerallua
S
1

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();
Sporulate answered 12/5, 2017 at 5:51 Comment(0)
D
0

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

 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);
Declarant answered 27/4, 2020 at 2:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.