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.

Chaoskatze
  • 41
  • 9
maryam
  • 387
  • 2
  • 3
  • 10

3 Answers3

56

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.

James_D
  • 201,275
  • 16
  • 291
  • 322
  • Out of curiosity, do you have any idea why they didn't make a getCenterX() and getCenterY() method? – Roland Jul 01 '15 at 04:04
  • 2
    @Roland 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. – James_D Jul 01 '15 at 20:00
  • @James_D ...It sometimes doesn't work!Why ? I don't understand really! – maryam Jul 10 '15 at 01:32
  • 1
    @maryam *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? – James_D Jul 10 '15 at 18:20
  • @SedrickJefferson Sorry, I don't understand what you mean by that. – James_D Mar 08 '17 at 21:50
  • 2
    @Roland JavaFX11 added `getCenterX()` etc. methods. – user1803551 Sep 26 '18 at 03:49
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();
Ragib
  • 107
  • 7
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);
Giovanni Contreras
  • 2,345
  • 1
  • 13
  • 22