Search code examples
alignmentvaadingrid-layoutvaadin7

Custom width of Vaadin GridLayout


I'm working with a 2x2 GridLayout in Vaadin.

    gridLayout = new GridLayout(2, 2);
        gridLayout.setWidth(100, Unit.PERCENTAGE);
        gridLayout.setMargin(true);
        gridLayout.setSpacing(true);

The cell in the upper-left corner contains a simple label aligned to the right. Upper-right cell contains a textfield aligned to the left. The second row simply contains a label below the textfield.

    gridLayout.addComponent(captionLabel, 0, 0);
    gridLayout.addComponent(inputField, 1, 0);

    gridLayout.setComponentAlignment(captionLabel, Alignment.MIDDLE_RIGHT);
    gridLayout.setComponentAlignment(inputField, Alignment.MIDDLE_LEFT);

Now I want to have both columns within the grid to have size set to 50% to have the whole layout aligned in the middle of my page - now it is slightly shifted to the left side and I can not figure out why...

Vaadin's wiki-page shows a related article, but I can not figure out how to work with it. Seems to be deprecated, because I can not access #getColumn(); - method?! https://vaadin.com/wiki/-/wiki/10674/Configuring+Grid+column+widths

For further info: The GridLayout is added as a separate component to a VerticalLayout.


Solution

  • Solved it by adding a HorizontalLayout-wrapper for the left column containing the label. The right colum contains a VerticalLayout with all other components.

        Label captionLabel = new Label(localized);
        captionLabel.setSizeUndefined();
        HorizontalLayout wrapper = new HorizontalLayout();
        wrapper.setSizeFull();
        wrapper.addComponent(captionLabel);
        wrapper.setComponentAlignment(captionLabel, Alignment.TOP_RIGHT);
        [...]        
        gridLayout.addComponent(wrapper, 0, 0);
        gridLayout.addComponent(inputLayout, 1, 0);
        gridLayout.setColumnExpandRatio(0, (float)0.5);
        gridLayout.setColumnExpandRatio(1, (float)0.5);