Vaadin Grid tutorial

In Vaadin Grid tutorial we learn the basics of the Vaadin Grid component. The Vaadin Grid example displays data from a MySQL database in a Grid.

Vaadin framework

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

Vaadin Grid

Grid component is used to display and edit tabular data laid out in rows and columns.

Vaadin Grid example

The following example demonstrates the usage of a Vaadin Grid component. We load data from a MySQL database and display it in the Grid 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.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.42</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.9.RELEASE</version>
</dependency>

We add two dependencies to the POM file: MySQL driver and the JdbcTemplate library. JdbcTemplate simplifies database programming in Java.

cars_mysql.java
-- SQL for the Cars table

CREATE TABLE Cars(Id BIGINT PRIMARY KEY AUTO_INCREMENT, 
        Name VARCHAR(150), Price INTEGER);
        
INSERT INTO Cars(Name, Price) VALUES('Audi', 52642);
INSERT INTO Cars(Name, Price) VALUES('Mercedes', 57127);
INSERT INTO Cars(Name, Price) VALUES('Skoda', 9000);
INSERT INTO Cars(Name, Price) VALUES('Volvo', 29000);
INSERT INTO Cars(Name, Price) VALUES('Bentley', 350000);
INSERT INTO Cars(Name, Price) VALUES('Citroen', 21000);
INSERT INTO Cars(Name, Price) VALUES('Hummer', 41400);
INSERT INTO Cars(Name, Price) VALUES('Volkswagen', 21600);

This is the data for the MySQL database table.

MyUI.java
package com.zetcode.main;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Grid;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.zetcode.bean.Car;
import com.zetcode.service.ReadCars;
import java.util.List;

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

    @Override
    protected void init(VaadinRequest vaadinRequest) {
        
        VerticalLayout vbox = new VerticalLayout();
        
        HorizontalLayout hbox = new HorizontalLayout();

        Grid grid = new Grid();
        
        grid.addColumn("Id", Long.class);
        grid.addColumn("Name", String.class);
        grid.addColumn("Price", Integer.class);

        Button loadButton = new Button("Load data");
        loadButton.addClickListener(e -> {

            grid.getContainerDataSource().removeAllItems();
            
            List<Car> cars = ReadCars.read();

            for (Car car : cars) {

                grid.addRow(car.getId(), car.getName(), car.getPrice());
            }
        });

        Button clearButton = new Button("Clear data");
        clearButton.addClickListener(e -> {
            grid.getContainerDataSource().removeAllItems();
        });

        vbox.addComponents(grid);
        hbox.addComponents(loadButton, clearButton);
        hbox.setSpacing(true);
        vbox.addComponent(hbox);
        vbox.setMargin(true);
        vbox.setSpacing(true);

        setContent(vbox);
    }

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

This is the MyUI class. It is the application entry point. We have a Grid component and two buttons. One button loads data from the database and inserts it into the Grid, the other button removes data from the Grid.

VerticalLayout vbox = new VerticalLayout();

HorizontalLayout hbox = new HorizontalLayout();

To create our layout, we use a HorizontalLayout and a VerticalLayout.

Grid grid = new Grid();

Grid component is created.

grid.addColumn("Id", Long.class);
grid.addColumn("Name", String.class);
grid.addColumn("Price", Integer.class);

With the addColumn() method, we add new columns to the Grid. The second parameter of the method is the date type of the column.

Button loadButton = new Button("Load data");
loadButton.addClickListener(e -> {

    grid.getContainerDataSource().removeAllItems();
    
    List<Car> cars = ReadCars.read();

    for (Car car : cars) {

        grid.addRow(car.getId(), car.getName(), car.getPrice());
    }
});

The load button loads data from the database and inserts it into the Grid. The database work in delegated to the ReadCars.read() method. New rows are added to the grid with the addRow() method.

Button clearButton = new Button("Clear data");
clearButton.addClickListener(e -> {
    grid.getContainerDataSource().removeAllItems();
});

The clear button removes all data from the Grid. The removeAllItems() method does the job.

vbox.addComponents(grid);
hbox.addComponents(loadButton, clearButton);

The components are added to the layout managers.

Car.java
package com.zetcode.bean;

public class Car {
    
    private Long id;
    private String name;
    private int price;

    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 getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

This is the Car bean; it contains id, name, and price attributes.

ReadCars.java
package com.zetcode.service;

import com.zetcode.bean.Car;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

public class ReadCars {

    public static List<Car> read()  {

        String url = "jdbc:mysql://localhost:3306/testdb?useSSL=true";
        
        SimpleDriverDataSource ds = new SimpleDriverDataSource();
        
        try {
            ds.setDriver(new com.mysql.jdbc.Driver());
        } catch (SQLException ex) {
            Logger.getLogger(ReadCars.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        ds.setUsername("testuser");
        ds.setPassword("test623");
        ds.setUrl(url);

        String sql = "SELECT * FROM Cars";
        
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
        List<Car> cars = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Car.class));
        
        return cars;
    }
}

The ReadCars contains code that connects to the MySQL database and retrieves all cars from the Cars table. We use Spring's JdbcTemplate to do the job.

String url = "jdbc:mysql://localhost:3306/testdb?useSSL=true";

This is the connection URL to the MySQL database. The database name is testdb.

String sql = "SELECT * FROM Cars";

This SQL statement selects all rows from the Cars table.

JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
List<Car> cars = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Car.class));

With the help of the BeanPropertyRowMapper, which automatically maps the result set columns to the properties of the Car class, we retrieve all rows from the Cars table and map them to the list of Car objects.

return cars;

The list of cars is returned to the caller.

Vaadin Grid
Figure: Vaadin Grid

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