Vaadin FormLayout 不居中对齐

Vaadin FormLayout does not align centered

我有一个 VerticalLayout 包装一个 Label 和一个 FormLayout。 VerticalLayout 默认将其组件居中对齐。标签按预期居中对齐。 FormLayout 没有。

当我在调试视图中查看组件树时,FormLayout 的宽度跨越了 VerticalLayout 的整个宽度。但是它的子项(文本字段)向左对齐并且宽度较小(我认为是默认值)。

我的代码:

@SpringView(name = RegisterView.VIEW_NAME)
@DesignRoot
public class RegisterView extends VerticalLayout implements View {

    protected static final String VIEW_NAME = "register";

    @PostConstruct
    void init() {
        setSizeFull();
        setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);
        createUIComponents();
        setSpacing(true);
    }

    private void createUIComponents() {
        addComponent(new Label("HEADER"));
        addComponent(createRegistrationForm());
        addComponent(new Label("TEST"));
    }

    private FormLayout createRegistrationForm() {
        final FormLayout layout = new FormLayout();
        final TextField firstNameTextField = new TextField("firstName");
        final TextField lastnameTextField = new TextField("lastname");
        layout.addComponents(firstNameTextField, lastnameTextField);
        return layout;
}

我哪里做错了,我怎样才能让 FormLayout 在 VerticalLayout 中居中?

我找到了一个解决方案(尽管 FormLayout 似乎表现得很奇怪):

我调用 setSizeUndefined() 而不是调用 setSizeFull() 让 FormLayout 只包装其子组件所需的 space。这允许环绕布局将 FormLayout 居中。

我无法做到的事情:我无法将 FormLayout 设置为全宽并将其子元素居中对齐。

我在使用 Vaadin 23 时遇到了同样的问题。使用 setSizeUndefined() 无效。相反,我通过将 FormLayout 包装在 Horizo​​ntalLayout 组件中来解决它。

解决方案:

private void createUIComponents() {
    add(new Label("HEADER"));
    add(new HorizontalLayout(createRegistrationForm()));
    //add(createRegistrationForm());
    add(new Label("TEST"));
}

注意:在较新的版本中,addComponent() 似乎已被 add() 取代。