kingkong
kingkong

Reputation: 1547

JavaFX - StackPane X, Y coordinates

I'm using a StackPane as a container for my figures, panels, etc. What I discovered is that coordinates X,Y (0,0) are placed right in the center of my panel.

Is it possible to move it to top left of the Pane ? Calculating all the dimensions from center is much more difficult.

Upvotes: 10

Views: 27868

Answers (2)

Mateusz Niedbal
Mateusz Niedbal

Reputation: 346

The previous answer is of course the best in this situation, but it is also wise to know that you can move Nodes on the StackPane using Translation.

Ex.

    Label topLeftLabel = new Label("Top Left");
    StackPane stack = new StackPane();
    stack.getChildren().add(topLeftLabel);
    
    topLeftLabel.setTranslateX(stack.getWidth()/2);
    topLeftLabel.setTranslateY(stack.getHeight()/2);

It would do the same thing (but may look a bit worse)

Upvotes: 0

jewelsea
jewelsea

Reputation: 159556

You can set the layout of Nodes added to the StackPane to a position within the Stackpane using the StackPane.setAlignment(node, position) method:

Label topLeftLabel = new Label("Top Left");
StackPane stack = new StackPane();
stack.getChildren().add(topLeftLabel);

StackPane.setAlignment(topLeftLabel, Pos.TOP_LEFT);

Even though this is possible, from your brief description of how you are trying to use the StackPane, it sounds like you would be better off using a regular Pane, or a Group or an AnchorPane for the kind of absolute positioning you appear to be wanting to achieve.

Possibly look into using a visual tool such as SceneBuilder as well. Even if you don't end up using the FXML it outputs, SceneBuilder should give you a much better idea of how JavaFX layout mechanisms work. SceneBuilder makes use of AnchorPane as its default layout pane used to provide absolute positioning for elements (which seems to be what you want to achieve).

Upvotes: 19

Related Questions