Search code examples
vaadinvaadin7

How to create caption of combobox at the same line?


Vaadin's comboBoxes were designed to show captions and items are line by line (you can see them in here). If I want to see them in a same line , what is the solution ?

Now I am trying to get as below ....

    HorizontalLayout hlMain = new HorizontalLayout();
    hlMain.addComponent(new Label("Gender:"));
    final ComboBox gender = new ComboBox("" , genderList);
    hlMain.addComponent(gender);

But I know above code is too ugly , So I am trying to use with CSS . I would like to know has there easy way to get it with Vaadin ? Any suggestions will be great help for me.


Solution

  • If you are willing to dedicate a layout to this, use a FormLayout:

    // run with: spring run vaadin.groovy
    @Grapes([
    @Grab('org.vaadin.spring:spring-boot-vaadin:0.0.5.RELEASE'),
    @Grab('com.vaadin:vaadin-server:7.4.4'),
    @Grab('com.vaadin:vaadin-client-compiled:7.4.4'),
    @Grab('com.vaadin:vaadin-themes:7.4.4'),
    ])
    import org.vaadin.spring.annotation.VaadinUI
    import com.vaadin.server.VaadinRequest
    import com.vaadin.ui.*
    
    @VaadinUI
    class MyUI extends UI {
        protected void init(VaadinRequest request) {
            setContent(new FormLayout( // XXX
                new ComboBox("Gender:").with{ addItem("M"); addItem("F"); it }
            ))
        }
    }
    

    Your current code would work, if you would not put the empty caption on the ComboBox (it makes Vaadin think, that there is something to show and render an empty line, break, and then the combobox). Yet FormLayout is the superior solution.

    // run with: spring run vaadin.groovy
    @Grapes([
    @Grab('org.vaadin.spring:spring-boot-vaadin:0.0.5.RELEASE'),
    @Grab('com.vaadin:vaadin-server:7.4.4'),
    @Grab('com.vaadin:vaadin-client-compiled:7.4.4'),
    @Grab('com.vaadin:vaadin-themes:7.4.4'),
    ])
    import org.vaadin.spring.annotation.VaadinUI
    import com.vaadin.server.VaadinRequest
    import com.vaadin.ui.*
    
    @VaadinUI
    class MyUI extends UI {
        protected void init(VaadinRequest request) {
            setContent(new HorizontalLayout(
                new Label("Gender"),
                new ComboBox().with{ addItem("M"); addItem("F"); it } // no label!
            ))
        }
    }