在容器、StackPane、VBox 等中对齐路径

Aligning a Path within a Container, StackPane, VBox etc

如果我尝试对齐 StackPane 中的路径,它会以某种方式根据其内部结构而不是使用布局边界进行对齐。无论如何改变这个?我尝试了 with/without Group wrapper、VBox、HBox、autosizeChildren 属性 等的各种组合

例如,我希望该行插入 (50, 50),但它显​​示在 (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();
}

在不使用 StackPane 的情况下,它的显示与我预期的一样。该行从 (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();
}

根据 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.

由于 Path 不可调整大小,因此不会调整大小,只是根据您设置的对齐方式进行定位。包装在 Group 中没有帮助,因为 Group 占据了其 children.

的边界

要么使用常规 Pane 而不是 StackPane(可能是最方便的解决方案):

Pane stack = new Pane(path);

或将路径包装在 Pane 中(调整大小等):

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