maryam
maryam

Reputation: 397

Get real position of a node in JavaFX

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.

Upvotes: 20

Views: 44180

Answers (3)

Giovanni Contreras
Giovanni Contreras

Reputation: 2579

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);

Upvotes: 0

Ragib
Ragib

Reputation: 107

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();

Upvotes: 1

James_D
James_D

Reputation: 209684

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.

Upvotes: 57

Related Questions