Why aren't components inside VerticalLayout aligned vertically in Vaadin 11?

Viewed 46

I have a view in Vaadin 11, which is displayed at URL like products/X where X is a product identifier.

@Route(value = "products")
public class ProductView extends VerticalLayout implements HasUrlParameter<String> {

    public ProductView() {

    }

    [...]
}

I cannot display any information on this page without having a product, therefore I add all components in the method setParameter:

@Override
public void setParameter(final BeforeEvent beforeEvent, 
                final String param) {
    final Product product = findProduct(param);

    if (product == null) {
        return;
    }
    final Text name = new Text(product.getName());
    final Text interestRate = new Text(String.format("Ставка: %.2f", 
                    product.getInterestRatePercentPerAnnum()));
    final Text duration = new Text(String.format("Срок: %d - %d месяцев",
                    product.getDurationMonths().getStart(),
                    product.getDurationMonths().getEndInclusive()));
    final Text provider = new Text(String.format("Организация: %s",
                    product.getProvider().getName()));
    final Text description = new Text("<html>Hi there! <b>Bold</b> text</html>");


    add(name);
    add(interestRate);
    add(duration);
    add(description);
    add(provider);
}

But the various data items are displayd in one line:

Screenshot

This means that for some reason VerticalLayout layous out the components horizontally.

How can I fix it (make sure that each component that I add is displayed on a separate line)?

1 Answers

Text is a specific component, since it corresponds to text nodes in the DOM (in the browser). Therefore, there are no HTML elements and the content added to the VerticalLayout will flow from left to right. That's how it looks in the browser tree: enter image description here

Use Div instead:

final Div name = new Div(new Text("Product"));
final Div interestRate = new Div(new Text(String.format("Ставка: %.2f",
            0.05d)));
final Div duration = new Div(new Text(String.format("Срок: %d - %d "
            + "месяцев", 10, 11)));
final Div provider = new Div(new Text(String.format("Организация: %s"
            , 10)));
final Div description = new Div(new Text("<html>Hi there! <b>Bold</b>"
            + " text</html>"));

By using Div, you're inserting div elements into the VerticalLayout so it can do it's work.

Related