Keyhan Keyhan - 13 days ago 5
Java Question

Vaadin button alignment in HorizontalLayout

When trying to set a button in HorizontalLayout, the button tends to be aligned with caption parts of other components in the layout rather than the component themselves. For example

HorizontalLayout hl = new HorizontalLayout();
h1.addComponent(new TextField("Test");
h1.addComponent(new Button("Do Something");


will result into the button being aligned not in line with the text field but with its caption text.

How can one fix the alignment so that it is aligned with the Text Field?

Answer

The HorizontalLayout has the setComponentAlignment() method you can use for this.

HorizontalLayout hl = new HorizontalLayout();
TextField tF= new TextField("Test");
h1.addComponent(tF);
Button btn= new Button("Do Something");
h1.addComponent(btn);
h1.setComponentAlignment(tF, Alignment.MIDDLE_CENTER);
h1.setComponentAlignment(btn, Alignment.MIDDLE_CENTER);

Perhaps you need another alignment mode, depending how you wish to align the components inside the HorizontalLayout