Search code examples
javajavafxposition

How to position JavaFX shapes within any Pane?


If I use a JavaFX element (for example, a Circle) directly in a Scene element it positions correctly. However, if I put it directly in a Pane (such as BorderPane below), then it isn't positioned right.

Example 1 (correctly positions Circle at (10,10)):

Circle c = new Circle(10,10,15);
Group g = new Group(c);
Scene s = new Scene(g,800,600);
stage.setScene(s);
stage.show();

Example 2 (doesn't work):

Circle c = new Circle(10,10,15);
Group g = new Group(c);
BorderPane b = new BorderPane();
b.setCenter(g);
Scene s = new Scene(b,800,600);
stage.setScene(s);
stage.show();

Any ideas?


Solution

  • Some panes handle the position of their children, regardless of what you set their x and y to, and some don't. If you want to set positions, you might want a Pane inside of a BorderPane.

    From the API docs for Pane:

    This class may be used directly in cases where absolute positioning of children is required since it does not perform layout beyond resizing resizable children to their preferred sizes. It is the application's responsibility to position the children since the pane leaves the positions alone during layout.

    More here: http://docs.oracle.com/javafx/2.0/api/javafx/scene/layout/package-summary.html