Search code examples
vaadinvaadin7

New component is placed in the middle instead below another one in Vaadin VerticalLayout


I have problem with sidebar menu in Vaadin, I have navigation bar that is 50px height. I wish to place sidebar (at this moment just VerticalLayout with buttons) that gonna take rest of the screen. The problem is when I add my sidebar to main layout it start from middle of the screen, like this:

I tried to use

setSizeFull();

method on my main layout but then it looks like that (even when I set my sidebar height to 100%)

There is code behind my sidebar:

public class Sidebar {

private VerticalLayout sidebar;
private Button menuItem01;
private Button menuItem02 = new Button("Item02");

//Create Sidebar
public VerticalLayout initSidebar() {
    sidebar = new VerticalLayout();
    sidebar.setWidth("10%");
    sidebar.setHeight("100%");
    sidebar.setMargin(false);
    sidebar.addComponent(createMenuItem());
    sidebar.addComponent(menuItem02);
    sidebar.addStyleName("sidebar");
    return sidebar;
}

public Button createMenuItem(){
    menuItem01 = new Button("Item01");
    return menuItem01;
}

}

And there is code behind my MainView

@Override
protected void init(VaadinRequest vaadinRequest) {
    template.setMargin(false);
    template.setSpacing(false);
    //template.setSizeFull();

    //Place all elements together
    template.addComponent(navigationBar.initNavigationBar());
    //template.addComponent(mainContent.initMainPanel());
    template.addComponent(sidebar.initSidebar());

    this.setContent(template);
}

Finally Navbar if needed:

public class NavigationBar {

private HorizontalLayout navbar;
private Button hamburgerButton;
private Label logo;

//Create Navigation Bar
public HorizontalLayout initNavigationBar() {
    navbar = new HorizontalLayout();
    navbar.setWidth("100%");
    navbar.setMargin(true);
    navbar.setHeight(50, Sizeable.Unit.PIXELS);
    navbar.addComponent(createHamburgerButton());
    navbar.addComponent(createLogo());
    navbar.addStyleName("navigation-bar");
    return navbar;
}

//Create Hamburger Button
public Button createHamburgerButton() {
    hamburgerButton = new Button();

    //Added some styling to hamburger button
    hamburgerButton.addStyleName("hamburger-button");
    hamburgerButton.setIcon(VaadinIcons.MENU);

    return hamburgerButton;
}

//Create ElenX logo
public Label createLogo() {
    logo = new Label("ElenX");
    logo.addStyleName("elenx-logo");
    logo.setWidthUndefined();
    logo.setEnabled(false);
    return logo;
}
}

Any ideas?


Solution

  • If a VerticalLayout has a height of 100% it will share the space with all contained components equally, unless you set expand ratios. You can tell the vertical layout to give all room to one component via verticalLayout.setExpandRatio(secondComponent, 1.0f). That will collapse your first component to just the room it needs and give the second one everything from the first to the bottom.