Adam
Adam

Reputation: 36703

Aligning a Path within a Container, StackPane, VBox etc

If I try to align a Path in a StackPane, somehow it is aligned based on its internal structure rather than using the layout bounds. Is there anyway of changing this? I've tried all sorts of combinations of with/without Group wrapper, VBox, HBox, autosizeChildren property etc.

For example, I want the line to be inset by (50, 50), but it gets shown at (0, 0)

@Override
public void start(Stage primaryStage) {
    MoveTo moveTo = new MoveTo();
    moveTo.setX(50);
    moveTo.setY(50);
    LineTo lineTo = new LineTo();
    lineTo.setX(100);
    lineTo.setY(100);
    Path path = new Path(moveTo, lineTo);
    StackPane stack = new StackPane(new Group(path));
    stack.setAlignment(Pos.TOP_LEFT);
    primaryStage.setScene(new Scene(stack, 100, 100));
    primaryStage.show();
}

aligned based on structure

Without using a StackPane it appears as I expect. the line starts at (50, 50)

@Override
public void start(Stage primaryStage) {
    MoveTo moveTo = new MoveTo();
    moveTo.setX(50);
    moveTo.setY(50);
    LineTo lineTo = new LineTo();
    lineTo.setX(100);
    lineTo.setY(100);
    Path path = new Path(moveTo, lineTo);
    primaryStage.setScene(new Scene(new Group(path), 100, 100));
    primaryStage.show();
}

aligned based on layout

Upvotes: 0

Views: 237

Answers (1)

James_D
James_D

Reputation: 209330

According to the StackPane Javadocs:

The stackpane will attempt to resize each child to fill its content area. If the child could not be sized to fill the stackpane (either because it was not resizable or its max size prevented it) then it will be aligned within the area using the alignment property, which defaults to Pos.CENTER.

Since the Path is not resizable, is doesn't get resized, and just gets positioned according to the alignment you set. Wrapping in a Group doesn't help because the Group takes on the bounds of its children.

Either use a regular Pane instead of the StackPane (probably the most convenient solution):

Pane stack = new Pane(path);

or wrap the path in a Pane (which gets resized, etc):

StackPane stack = new StackPane(new Pane(path));

Upvotes: 1

Related Questions