jhegedus
jhegedus

Reputation: 20653

How to get the scene coordinates of a Node in JavaFX 8? localToScene does not seem to work

The (Scala) code below produces a wrong result (namely [x = 0.0, y = 0.0]).

Why ?

How can it be fixed ?

According to the JavaDoc this code should print 50, 80 for the x and y coordinates of Circle.

object CircleTestLauncher extends App{
  Application.launch(classOf[CircleTest])
}
class CircleTest extends Application with App
{
  override def start(p1: Stage): Unit = {

    val c1= new Circle(50,80,10)
    val sp=new Group

    sp.getChildren.add(c1)
    p1.setScene(new Scene(sp,300,300))
    p1.show()
    println("in start method, scene coord. of circle ="+c1.localToScene(Point2D.ZERO))

  }
}

prints:

in start method, scene coord. of circle =Point2D [x = 0.0, y = 0.0]

EDIT :

The accepted answer solves the problem, however, according to this blog entry my solution should work too, the question remains: why does the above code not work ?

What is the difference between the two coordinates (getCenter vs localToScene) ?

What is localToScene used for at all ?

I googled for this and found very few info on this.

JavaFX books also don't explain this.

Upvotes: 0

Views: 5050

Answers (2)

jhegedus
jhegedus

Reputation: 20653

Here is the answer for the why (this answer I found in the JavaFX 8 source code).

The reason is that local2Scene applies to transformations only.

So the actual position of a circle is its centre plus transformations (the centre coordinate vector multiplied by the transformation matrix).

object CircleTestLauncher extends App{
  Application.launch(classOf[CircleTest])
}

class CircleTest extends Application with App
{
  override def start(p1: Stage): Unit = {

    val c1= new Circle(50,80,10)
    val sp=new Group

    sp.getChildren.add(c1)
    c1.setTranslateX(10)
    c1.setTranslateY(20)
    p1.setScene(new Scene(sp,300,300))
    p1.show()
    println("in start method, scene coord. of circle ="+c1.localToScene(Point2D.ZERO))

  }
}

Prints:

in start method, scene coord. of circle =Point2D [x = 10.0, y = 20.0]

Upvotes: 0

ItachiUchiha
ItachiUchiha

Reputation: 36722

I am not sure about how it is done in Scala, but in java, the following code works fine

System.out.println("X :" +c1.getCenterX()+ " Y: "+c1.getCenterY());

The output is

X :50.0 Y: 80.0

Upvotes: 1

Related Questions