Over a million developers have joined DZone.
Refcard #085

Getting Started With Vaadin Framework 8

Modern Web Apps in Java

Vaadin gives you the opportunity to develop modern web applications that provide a great user experience and look great. Using a built-in selection of components, themes, data binding, and more, Vaadin is the ideal in web application development frameworks.


Brought to you by

Free .PDF for easy Reference

Written by

Matti Tahvonen Vaadin Expert, Vaadin
Marko Grönroos Technical Writer, IT Mill
Refcard #085

Getting Started With Vaadin Framework 8

Modern Web Apps in Java

Vaadin gives you the opportunity to develop modern web applications that provide a great user experience and look great. Using a built-in selection of components, themes, data binding, and more, Vaadin is the ideal in web application development frameworks.

Free .PDF for easy Reference

Written by

Matti Tahvonen Vaadin Expert, Vaadin
Marko Grönroos Technical Writer, IT Mill

Brought to you by

Table of Contents

About Vaadin Framework

Bootstrapping a Project


Layout Components

Add-on Components


Data Binding

Widget Integration

Section 1

About Vaadin Framework

Vaadin Framework is a productive and easy-to-use UI library for developing web applications in Java or your JVM language of choice. Vaadin’s strong abstraction of web technologies gives you a component-based approach to build your apps, almost like you’re building traditional desktop apps, but through state-of-the-art web technologies. You use an object-oriented approach to compose your UI from smaller UI components and layouts, and hook your logic to the UI with event listeners.

In addition to providing high-level UI components, which saves you from time-consuming HTML, CSS, and JavaScript programming, Vaadin also abstracts away the communication between the server and the browser. This makes both the UI and backend development easier (no need to expose REST services) and increases security.

Vaadin Framework is open source and licensed under the liberal Apache 2 license.

Image title

Figure 1: Vaadin Client-Server Architecture

For extending the framework, there are numerous add-ons built by Vaadin and the community. The Directory service currently lists nearly 700 add-ons for Vaadin Framework.

Section 2

Bootstrapping a Project

You can create a Vaadin application project easily from Maven archetypes. To create a simple app stub, use the following command (or use the same groupId and archetypeId in your IDE):

mvn archetype:generate -DarchetypeGroupId=com.vaadin -DarchetypeArtifactId=vaadin-archetype-application -DarchetypeVersion=LATEST

start.spring.io also provides an option to include Vaadin dependencies to your Spring project. The most commonly used IDEs (IntelliJ, Eclipse, and Netbeans) also have built in support or plugins that can help to create Vaadin applications.

The UI Class: The Entry Point to Your Application

The UI class (extends the com.vaadin.UI) is the entry point to your application. The framework creates an instance when the user opens the page in the browser and calls the init method init().

@Title(“My Vaadin UI”)
  public class HelloWorld extends com.vaadin.UI {    
    protected void init(VaadinRequest request) {
    // Create the content root layout for the UI
    VerticalLayout content = new VerticalLayout();
    // Display the greeting
    content.addComponent(new Label(“Hello World!”));

Normally, you need to:

  • Extend the UI class.

  • Build an initial UI from components.

  • Define event listeners to implement the UI logic.

Optionally, you can also:

  • Set a custom theme for the UI.

  • Bind components to data.

  • Bind components to resources.

Image title

Figure 2: Class Diagram

Tip: You can get a reference to the UI object associated with the currently processed request from anywhere in the application logic with UI.getCurrent(). You can also access the current VaadinSession, VaadinService, and VaadinServlet objects in the same way.


To expose UI classes for end users, you’ll need a VaadinServlet deployed to a servlet container. The VaadinServlet handles server requests and manages user sessions and UIs. If you use Vaadin Spring or Vaadin CDI (available in the Vaadin Directory), the servlet is configured automatically, and you only need to expose your UI class using @SpringUI or @CDIUI(“”) annotation. In a basic servlet container project, like the one that is generated by vaadin-archetype-application, the servlet can be declared as such:

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


Most of the time you don’t need to work at the servlet level at all, but you can add customization to the servlet if you want. In Spring and CDI projects, you can just expose a customized version of SpringVaadinServlet or VaadinCDIServlet and the automatic default version is then ignored.

Vaadin UIs can also be deployed as portlets in a portal. Refer to vaadin.com/docs for Portlet deployment.

Events Listeners

In the event-driven model, user interactions with user interface components trigger server-side events, which you can handle with event listeners.

In the following example, we handle click events for a button with an anonymous class:

Button button = new Button(“Click Me”); 
button.addClickListener(event-> {
  Notification.show(“Thank You!”);

Different components provide different listeners. For example, value changes in a field component can be handled with a ValueChangeListener, and TabSheet allows you to listen to tab changes using SelectedTabChangeListener. Many field components allow to track focus using FocusListener.

In addition to the event-driven model, UI changes can be made from other places than UI initiated threads. Changes are reflected automatically if you have enabled server push (using vaadin-push module and @Push annotation to UI class) or use polling configured to the UI class. The push mode primarily uses WebSockets for communication and falls back to long polling if it’s not supported.

public void notifyUI(YourAppUI activeUI, String msg) {
  // ensure proper synchronization using the UI.access method
  // when called from a non-UI initiated event
  activeUI.access(() -> {
    activeUI.showMessageInUI(msg); // method in your UI class
Section 3


Vaadin components include field, layout, and other components. The component classes and their inheritance hierarchy is illustrated in Figure 2.

Component Properties

Common component properties are defined in the Component interface and the AbstractComponent base class for all components.




A label usually shown above, left of, or inside a component, depending on the component and the containing layout.


A longer description that is usually displayed as a tooltip when the mouse hovers over the component.


If false, the component is shown as grayed out and the user cannot interact with it. (Default: true.)


An icon for the component, usually shown left of the caption, specified as a resource reference.


The current country and/or language for the component. Meaning and use is application-specific for most components. (Default: UI locale.)


Whether the component is visible or not. (Default: true.)

Field Properties

Field implementations often extend from AbstractField<T> and contain the following commonly used properties.




The actual value of the field. The type depends on the field and possible configuration. Value changes can be monitored using ValueChangeListener, but often values are bound automatically using com.vaadin.data.Binder.


A Boolean controlling whether the component should be marked as required in the UI (most often using red * character).


If true, the user cannot change the value. (Default: false.)


The tab index property is used to specify the order in which the fields are focused when the user presses the Tab key.


The size of components can be set in fixed or relative units by either dimension (width or height), or be undefined to shrink to fit the content.





Set the component size in either fixed units (px,pt, pc, cm, mm, in, em, or rem) or as a relative percentage (%) of the available area provided by the containing layout. The null value or -1 means undefined size (see below), causing the component to shrink to fit the content.


Sets both dimensions to 100% relative size.


Sets both dimensions as undefined, causing the component to shrink to its minimum size.

Figure 4 shows the default sizing of components.

Notice that a layout with an undefined size must not contain a component with a relative (percentual) size. For more tips on how to use relative sizes, refer to the Layout section.


Icons, embedded images, hyperlinks, and downloadable files are referenced as resources.

Button button = new Button(“Button with an icon”);
button.setIcon(new ThemeResource(“img/myimage.png”));

External and theme resources are usually static resources. Connector resources are served by the Vaadin servlet.

Image title

Figure 3: Resource Classes and Interfaces

Class Name



Any URL.


A static resource served by the application server from the current theme. The path is relative to the theme folder.


Loaded from the file system.


Loaded from the class path.


Provided dynamically by the application.


Font icon sets, such as VaadinIcons, contain a selection of special resources that can be used as icons.

Section 4

Layout Components

The layout of a UI is built hierarchically from layout components, or more generally component containers, with the actual interaction components as the leaf nodes of the component tree.

You start by creating a root layout and setting it as the UI content with setContent(). Then you add the other components to that with addComponent(). Single-component containers, most notably Panel and Window, only hold a single content component, just as UI, which you must set with setContent().

The sizing of layout components is crucial. Their default sizes are marked in Figure 4, and can be changed with the sizing methods described earlier. Notice that if all the components in a layout have relative size in a particular direction, the layout may not have undefined size in that direction!

Tip: Besides building your layouts in Java, you can also layout your view in declarative HTML format or visually by using Vaadin Designer inside Eclipse or IntelliJ.


Certain layout components support setting margins programmatically. Setting setMargin(true) enables all margins for a layout, and with a MarginInfo parameter you can enable each margin individually. The margin sizes can be adjusted with the padding property (as top, bottom, left, and right padding) in a CSS rule with a corresponding v-top-margin, v-bottom- margin, v-left-margin, or v-right-margin selector. For example, if you have added a custom mymargins style to the layout:

.mymargins.v-margin-left {padding-left: 10px;}
.mymargins.v-margin-right {padding-right: 20px;}
.mymargins.v-margin-top {padding-top: 30px;}
.mymargins.v-margin-bottom {padding-bottom: 40px;}


Certain layout components also support the setSpacing(true) method that controls spacing between the layout slots. Spacing can be adjusted with CSS as the width or height of the elements with the v-spacing style. For example, for a vertical layout:

.v-vertical > .v-spacing {height: 50px;}

For a GridLayout, you need to set the spacing as left/top padding for a .v-gridlayout-spacing-on element:

.v-gridlayout-spacing-on { 
  padding-left: 100px;
  padding-top: 50px; 


When an area provided by the layout component is larger than a contained component, the component can be aligned within the cell with the setComponentAlignment() method as in the example below:

VerticalLayout layout = new VerticalLayout();
Button button = new Button(“My Button”);
layout.setComponentAlignment(button, Alignment.MIDDLE_CENTER);

Expanding Components to Available Space

The ordered layouts and GridLayout support expand ratios allow some components to take the remaining space left over from other components. The ratio is a float value and components have 0.0f default expand ratio. The expand ratio must be set after the component is added to the layout.

VerticalLayout layout = new VerticalLayout();
layout.addComponent(new Label(“Title”)); // Doesn’t expand
TextArea area = new TextArea(“Editor”); 
layout.setExpandRatio(area, 1.0f)

VerticalLayout and HorizontalLayout also contain a helper method called addComponentsAndExpand(Component…) that adds a component and adjusts expand ratios and component sizes that suit most common use cases. The above can be flattened to:

VerticalLayout layout = new VerticalLayout();
layout.addComponent(new Label("Title")); // Doesn’t expand
TextArea area = new TextArea("Editor"); 

The Grid component also supports expand ratios for columns.

Custom Layout

The CustomLayout component allows the use of an HTML template that contains location tags for components, such as <div location=”hello”/>. The components are inserted in the location elements with the addComponent() method as shown below:

CustomLayout layout = new CustomLayout(
layout.addComponent(new Button("Hello"), "hello");

The layout content is given as an InputStream or it can also be a named resource file in your theme directory.

Section 5

Add-on Components

Your application might require less frequently needed features or UI components, which are not included in the core distribution. Hundreds of Vaadin add-on components are available in the Vaadin Directory, both free and commercial. To use a component, just copy the dependency information for Maven or download the jar files from Directory into your project.

Many of the add-ons contain client side extensions. These add-ons require you have a widgetset that combines both built in and custom client side extensions into one compact client side engine. If you created your add-on with vaadin-archetype-application, your application is ready for add-on usage out of the box, but remember to execute "mvn clean install" (or the same via your IDE) to ensure the client side engine is rebuilt.

If your project doesn't have vaadin-maven-plugin (e.g. a start.spring.io project or simplified example app), add the following build plugin to your project's pom.xml file:

                <!-- Needed for theme: -->
                <!-- Needed for theme: -->
Section 6


Vaadin allows customization of the appearance of the user interface with themes. Themes can include Sass or CSS style sheets, custom layout HTML templates, and graphics.

Basic Theme Structure

Custom themes are placed under the /VAADIN/themes/ folder of the web application (src/main/webapp in Maven projects). This location is fixed and the VAADIN folder specifies that these are static resources specific to your Vaadin application. The structure is illustrated in Figure 5.

Each theme has its own folder with the name of the theme. A theme folder must contain a styles.scss (for Sass) or a styles.css (for plain CSS) style sheet. Custom layouts must be placed in the layout’s sub-folder, but other contents may be named freely.

Custom themes need to inherit a base theme. The suggested base theme is Valo, which is easily customizable using Sass variables. Such a theme is created for you automatically if you bootstrap your project is built on top of the vaadin-archetype-application archetype.

Sass Themes

Sass (Syntactically Awesome StyleSheets) is a stylesheet language based on CSS3, with some additional features such as variables, nesting, mixins, and selector inheritance. Sass themes need to be compiled to CSS. Vaadin includes a Sass compiler that compiles stylesheets during the build process. You can also use on-the-fly compilation during development, by disabling the compilation from the build script.

To enable multiple themes on the same page, all the style rules in a theme should be prefixed with a selector that matches the name of the theme. It is defined with a nested rule in Sass. Sass themes are usually organized in two files: a styles.scss and a theme-specific file such as mytheme.scss.

With this organization, the styles.scss would be as follows:

@import "mytheme.scss";
@import "addons.scss";

// This file prefixes all rules with the theme name to avoid causing conflicts with other themes.
// The actual styles should be defined in mytheme.scss

.mytheme {
  @include addons;
  @include mytheme;

The mytheme.scss, which contains the actual theme rules, would define the theme as a Sass mix-in as follows:

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

@mixin mytheme {
  @include valo;

  // Insert your own theme rules here
  .mycomponent { color: red; }  

Image title

Figure 4: Theme Contents

Applying a Theme

Every component has a default CSS class based on the component type, and you can add custom CSS classes for UI components with addStyleName(), as shown below.

You set the theme for a UI with the @Theme annotation.

public class MyUI extends UI {

    protected void init(VaadinRequest vaadinRequest) {
    Label label = new Label("This is my themed component");
Section 7

Data Binding

Vaadin allows binding your Java domain classes directly to components. This way, you avoid writing a lot of boilerplate code.

Listing Data in Grid

Grid, the component that shows your data in tabular format, often plays a central part in a business application. The easiest way to use Grid is to pass the data as a list, stream or an array. In the following code example, Person is your domain object (Java Bean):

Grid<Person> grid = new Grid<>(Person.class);
// define columns and the order as bean properties (default: show all)
grid.setColumns("firstName", "lastName", "email");

Alternatively, you can define columns programmatically. In this case, you don’t need to pass the domain type as a constructor parameter:

Grid<Person> grid = new Grid<>();
grid.addColumn(Person::getFirstName).setCaption("First name");
// ...

The addColumn method returns a Column object that can be used to further configure the column and the data representation. In the above example, we only configure the caption of the column. With bean based listing your can get a reference to the Column with getColumn(“propertyName”).

Lazy Loading Data in Grid

The setItems method stores the given data in your server memory for rapid access. If your data grid contains a lot of data and you wish to save some server memory, you can also do a lazy binding with your backend using setDataProvider method:

  (sortOrders, offset, limit) ->
    service.findAll(offset, limit).stream(),
    () -> service.count()

The example above uses the easiest solution, in which you only provide two lambda expressions: the first to provide the given range of items and the second one that provides the total number of items available. Alternatively, you can provide a custom implementation of the DataProvider interface.

Selection Components

Selection components (ComboBox, RadioButtonGroup, ListSelect...) let your users pick one or several selections from a set of given items. Grid is also a selection component. You can use it as a single or multi-selection component using asSingleSelect() or asMultiSelect() method.

To set the available items, you use the same setItems or setDataProvider methods, as with Grid. Most select components by default render the selections using item’s toString method. Selecting a String from a list of strings could be accomplished as follows:

ComboBox<String> comboBox = new ComboBox<>();
comboBox.addValueChangeListener(e -> Notification.show(e.getValue()));

If toString presentation doesn’t fit to your use case, you can in most select components customize the caption as follows:

ComboBox<Person> cb = new ComboBox<>();
cb.setItemCaptionGenerator(p -> p.getFirstName() + " " + p.getLastName());

A similar concept is available for icons.

Binder for Handy Forms

Binder is a helper class that allows you to bind a single Java object’s properties to be displayed in multiple Vaadin components. The most typical use case is a form. Binder also supports two-way binding, so that values input by the end user automatically get written back to your domain model.

Binder will also help you to do value conversion and validation for the data. The following binds firstName(String) and age (Integer) to two text fields.

Binder<Person> b = new Binder<>();
// additional configuration
.asRequired("First name must be defined")
.bind(Person::getFirstName, Person::setFirstName);
.withConverter(new StringToIntegerConverter("Must be valid integer!"))
.withValidator(integer -> integer > 0, "Age must be positive")
.bind(p -> p.getAge(), (p, i) -> p.setAge(i));

Alternatively, you can make an automatic binding to your UI classes member fields. The binding is made based on naming convention, but it can be overridden with @PropertyId annotation.

private TextField age = new TextField();
private TextField firstName = new TextField();

private void bindFields(Person person) {
Binder<Person> b = new Binder<>(Person.class);
// additional configuration supported also in name based binding
.withConverter(new StringToIntegerConverter("Must be integer"));
// this binds all found fields
Section 8

Widget Integration

The easiest way to create new components is composition with the CustomComponent or by extending from some layout component. If that is not enough, you can create an entirely new component by creating a client-side widget (in GWT or JavaScript), a server-side counterpart, and binding the two together with a connector, using a shared state and RPC calls.

Image title

Figure 5: Integrating a Client-Side widget with a Server-Side API

Shared state is used for communicating component state from the server-side component to the client-side connector, which should apply them to the widget. The shared state object is serialized by the framework.

You can make RPC calls both from the client-side to the server-side, typically to communicate user interaction events, and vice versa. To do so, you need to implement an RPC interface.

Creating a Widget Project

You can create widgets directly to your application project, but a much better habit is to create a separate add-on project for your custom widgets and then add dependency to it from your application projects. Then you can build better tests and are prepared for reuse in your other Vaadin projects or even sharing your add-ons with others via the Directory service.

For widgets, there is a specially tailored project template, vaadin-archetype-widget. Create a project using that archetype and follow its instructions in its README file. The archetype also creates stubs for required classes.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}