Vaadin ComboBox tutorial

In Vaadin ComboBox tutorial we learn the basics of the Vaadin ComboBox component. The Vaadin ComboBox examples display selected values in a label component.

Vaadin

Vaadin is a popular Java web development framework, which is used for building single page web applications.

Vaadin ComboBox

ComboBox is a selection component that allows selecting an item from a drop-down list. In the editable mode it is possible to enter a new value.

Vaadin ComboBox example

The following program demonstrates the usage of a Vaadin ComboBox component. The selected value from the ComboBox is displayed in a label component.

NetBeans IDE can be used to easily create a Vaadin web application. We need to install NetBeans Vaadin plugin and then create a new Vaadin Web Application Project.

MyUI.java
package com.zetcode.ui;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.HasValue;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;

@Theme("mytheme")
@Title("Vaadin ComboBox")
public class MyUI extends UI {

    @Override
    protected void init(VaadinRequest vaadinRequest) {
        
        HorizontalLayout layout = new HorizontalLayout();
        
        Label lbl = new Label();
        
        ComboBox<String> cb = new ComboBox<>();
        cb.setTextInputAllowed(false);
        cb.setItems("Ubuntu", "Debian", "Arch", "Mint");
        cb.setEmptySelectionAllowed(false);

        cb.addValueChangeListener((HasValue.ValueChangeEvent<String> event) -> {
            
            String item = event.getValue();
            lbl.setValue(item);
        });
        
        layout.addComponents(cb, lbl);
        layout.setComponentAlignment(lbl, Alignment.MIDDLE_CENTER);
        layout.setMargin(true);
        
        setContent(layout);
    }

    @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
    @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
    public static class MyUIServlet extends VaadinServlet {
    }
}

This is the MyUI class.

HorizontalLayout layout = new HorizontalLayout();

In our example, we display two components in a row with HorizontalLayout.

Label lbl = new Label("");

The Label component dispays the value selected from the combo box.

ComboBox<String> cb = new ComboBox<>();

A ComboBox component is created.

cb.setTextInputAllowed(false);

With the setTextInputAllowed() method we disable the editable mode of the ComboBox.

cb.setItems("Ubuntu", "Debian", "Arch", "Mint");

With setItems(), we add four string elements into the ComboBox.

cb.setEmptySelectionAllowed(false);

By default, ComboBox shows an empty item that allows the user to choose no item. We disable this option with setEmptySelectionAllowed().

cb.addValueChangeListener((HasValue.ValueChangeEvent<String> event) -> {
    
    String item = event.getValue();
    lbl.setValue(item);
});

With addValueChangeListener(), we add a listener for value changes in ComboBox. We get the currently selected item of the ComboBox with the getValue() method. The retrieved value is set to the label using the setValue() method.

layout.addComponents(cb, lbl);

The two components are added to the HorizontalLayout with the addComponents() method.

layout.setComponentAlignment(lbl, Alignment.MIDDLE_CENTER);

We put the label into the middle of the row with setComponentAlignment() and Alignment.MIDDLE_CENTER alignment.

layout.setMargin(true);

We put some margin around the HorizontalLayout.

mytheme.scss
@import "../valo/valo.scss";

@mixin mytheme {
  @include valo;

  .v-horizontal > .v-spacing {
    width: 2em;
  }
}

We increase the spacing between the components in the HorizontalLayout.

Vaadin ComboBox
Figure: Vaadin ComboBox

Vaadin ComboBox example II

In the second example, the ComboBox is filled with a list of city objects retrieved from a service method. With the setItemCaptionGenerator() we produce the strings shown in the ComboBox.

City.java
package com.zetcode.bean;

import java.io.Serializable;

public class City implements Serializable {

    private static final long serialVersionUID = 1L;
    
    private Long id;
    private String name;
    private int population;

    public City() {
    }

    public City(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public String toString() {
        return "City{" + "id=" + id + ", name=" + name + 
                ", population=" + population + '}';
    }
}

This is the City bean; it contains id, name, and population attributes.

ICityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.List;

public interface ICityService {

    public List<City> findAll();
}  

The ICityService defines the findAll() contract method.

CityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.ArrayList;
import java.util.List;

public class CityService implements ICityService {
    
    @Override
    public List<City> findAll() {

        List<City> cities = new ArrayList<>();
        
        cities.add(new City(1L, "Bratislava", 432000));
        cities.add(new City(2L, "Budapest", 1759000));
        cities.add(new City(3L, "Prague", 1280000));
        cities.add(new City(4L, "Warsaw", 1748000));
        cities.add(new City(5L, "Los Angeles", 3971000));
        cities.add(new City(6L, "New York", 8550000));
        cities.add(new City(7L, "Edinburgh", 464000));
        cities.add(new City(8L, "Berlin", 3671000));
        
        return cities;
    }
}

The CityService returns a list of City objects.

MyUI.java
package com.zetcode.ui;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.HasValue;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.zetcode.bean.City;
import com.zetcode.service.CityService;

@Theme("mytheme")
@Title("Vaadin ComboBox")
public class MyUI extends UI {

    @Override
    protected void init(VaadinRequest vaadinRequest) {

        CityService cityService = new CityService();
        
        HorizontalLayout layout = new HorizontalLayout();
        
        Label lbl = new Label();
        
        ComboBox<City> cb = new ComboBox<>();
        cb.setTextInputAllowed(false);
        cb.setItems(cityService.findAll());
        cb.setEmptySelectionAllowed(false);
        
        cb.setItemCaptionGenerator(City::getName);

        cb.addValueChangeListener((HasValue.ValueChangeEvent<City> event) -> {
            
            City city = event.getValue();
            String item = String.format("%s: %s", city.getName(), 
                    city.getPopulation());
            
            lbl.setValue(item);
        });
        
        layout.addComponents(cb, lbl);
        layout.setComponentAlignment(lbl, Alignment.MIDDLE_CENTER);
        layout.setMargin(true);
        
        setContent(layout);        
    }

    @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
    @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
    public static class MyUIServlet extends VaadinServlet {
    }
}

This is the MyUI class.

ComboBox<City> cb = new ComboBox<>();

A parameterized ComboBox is created.

cb.setItems(cityService.findAll());

The ComboBox is filled with data from the service method.

cb.setItemCaptionGenerator(City::getName);

With the setItemCaptionGenerator() we choose the names of the cities to be displayed as item labels in the ComboBox.

cb.addValueChangeListener((HasValue.ValueChangeEvent event) -> {
    
    City city = event.getValue();
    String item = String.format("%s: %s", city.getName(), 
            city.getPopulation());
    
    lbl.setValue(item);
});

In the label, we display the city name and its population, separated with a colon.

In this tutorial, we have showed the basics of the Vaadin ComboBox component. You might also be interested in the related tutorials: Vaadin Grid tutorial, Vaadin Button tutorial, Vaadin Slider tutorial, Vaadin CheckBox tutorial, Java tutorial.