Question

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

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

Was it helpful?

Solution

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

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top