Aligning components is easy in Vaadin. We can align them on the left, on the right, on the top, on the bottom, and also center them vertically or horizontally. In this recipe, we will create a demo application in which we can see how aligning works. We will create three buttons in three different positions, as we can see in the following screenshot:
Carry out the following steps to create and learn how alignment works in Vaadin.
Demo
.public class Demo extends UI {…}
AligningDemo
that is based on the VerticalLayout
.public class AligningDemo extends VerticalLayout {…}
setComponentAlignment()
method. As a parameter, we use predefined alignments from the Alignment
class.public AligningDemo() { Button leftButton = new Button("top, left"); addComponent(leftButton); setComponentAlignment(leftButton, Alignment.TOP_LEFT);
Button centerButton = new Button("middle, center"); addComponent(centerButton); setComponentAlignment(centerButton, Alignment.MIDDLE_CENTER);
Button rightButton = new Button("bottom, right"); addComponent(rightButton); setComponentAlignment(rightButton, Alignment.BOTTOM_RIGHT);
setMargin(true); setSizeFull(); }
AligningDemo
class in the root class.public class Demo extends UI { @Override public void init(VaadinRequest request) { setContent(new AligningDemo()); } }
We can set the alignment of the component inside a specific layout with the setComponentAlignment()
method. The method takes the component contained in the layout to be formatted as its parameters, and also takes the horizontal and vertical alignment. The easiest way to set alignments is to use the constants defined in the Alignment
class.
Alignment
class, available at https://vaadin.com/api/7.0.0/com/vaadin/ui/Alignment.html18.219.48.116