Vaadin 7 UI Design By Example: Beginner's Guide

3.7 (3 reviews total)
By Alejandro Duarte
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Writing Your First Vaadin-powered Application

About this book

Vaadin is a mature, open-source, and powerful Java framework used to build modern web applications in plain Java. Vaadin brings back the fun of programming UI interfaces to the web universe. No HTML, no CSS, no JavaScript, no XML. Vaadin lets you implement web user interfaces using an object oriented model, similar to desktop technologies such as Swing and AWT.

Vaadin 7 UI Design By Example: Beginner’s Guide is an engaging guide that will teach you how to develop web applications in minutes. With this book, you will Develop useful applications and learn basics of Java web development. By the end of the book you will be able to build Java web applications that look fantastic.

The book begins with simple examples using the most common Vaadin UI components and quickly move towards more complex applications as components are introduced chapter-by-chapter.

Vaadin 7 UI Design By Example: Beginner’s Guide shows you how to use Eclipse, Netbeans, and Maven to create Vaadin projects. It then demonstrates how to use labels, text fields, buttons, and other input components. Once you get a grasp of the basic usage of Vaadin, the book explains Vaadin theory to prepare you for the rest of the trip that will enhance your knowledge of Vaadin UI components and customization techniques.

Publication date:
July 2013
Publisher
Packt
Pages
246
ISBN
9781782162261

 

Chapter 1. Writing Your First Vaadin-powered Application

So you want to start creating cool web applications in Java? Well, you've come to the right place. Vaadin is a mature, powerful Java framework to build modern web applications leveraging your Java programming skills, and understanding of concepts such as listeners, components, and other well-known constructions acquired from the desktop APIs such as Swing and AWT.

First things first. Downloading, installing, and configuring your development environment are the first steps to get started with Vaadin. In this chapter we will cover the following topics:

  • Creating and running Vaadin applications in Eclipse

  • Creating and running Vaadin applications in NetBeans

  • Creating and running Vaadin applications using Maven

  • Generated application explained

  • Buttons

  • Labels

  • Text fields

  • Notifications

We will cover the details of configuring your development environment using Eclipse, NetBeans, and Maven. Feel free to jump straight to the section explaining your favorite IDE and skip those covering the other ones.

Let's get our hands dirty!

 

Creating and running Vaadin applications in Eclipse


If you are using NetBeans, another IDE, or no IDE at all, you can safely skip this section.

Installing Eclipse

Just in case you haven't already done so, you will need to download and install Eclipse, the preferred IDE for developing Vaadin applications.

 

Time for action – downloading and installing Eclipse


Steps to download and install Eclipse are as follows:

  1. Go to http://eclipse.org/ and download the latest (or your favorite) version of Eclipse for Java EE Developers.

  2. Extract the downloaded file to the directory you would like Eclipse to be installed in.

  3. Execute eclipse.exe or eclipse according to your operating system flavor.

What just happened?

Guess what? We've just downloaded and installed Eclipse. Seriously, that was the very first step; now we need to install the Vaadin plugin for Eclipse.

Installing the Vaadin plugin for Eclipse

In this section we will see how to install the Vaadin plugin for Eclipse.

 

Time for action – installing the plugin


Steps to install the Vaadin plugin for Eclipse are as follows:

  1. In Eclipse, go to Help | Eclipse Marketplace….

  2. Type Vaadin in the Find field inside the Search tab and press Enter.

  3. Click on the Install button besides the Vaadin Plugin for Eclipse heading.

  4. Eclipse will calculate some requirements and dependencies. Once it does, make sure the Vaadin Plugin for Eclipse is checked and click on Next.

  5. Read and accept the terms of the license agreement and click on Finish to start installing the plugin.

    Tip

    I always keep processes like this running in the background. This helps me to be more productive because I can read or write some code, change configuration, deploy to a server, or perform any other IDE related action while having the background process moving forward.

  6. The installation process can take some minutes. You will be prompted to accept installing software that contains unsigned content. Click on OK when asked to and let Eclipse continue with the installation.

  7. Finally, Eclipse will ask you if you want to restart the IDE. Do it. Once you restart Eclipse, you'll see a little reindeer logo on the toolbar, that's the Vaadin logo and means that the plugin is ready.

What just happened?

We've just prepared Eclipse to start hacking! Using the Vaadin Plugin for Eclipse we'll be able to create new Vaadin projects, custom components, and themes. But before that, we will have to install a web server to deploy our Vaadin applications.

Note

You might have noted that the Vaadin Plugin for Eclipse installed an additional plugin: IvyDE. Ivy is a tool for managing dependencies, usually all the JAR files that your project needs. Don't worry too much if you don't know Ivy, just go through the following steps and we will get some fun in a couple of minutes, I promise.

Installing Run Jetty Run plugin

Although we can deploy to most Java servers, we will use Jetty throughout this book. Jetty is a fast open source web server that implements the Java Servlet and JavaServer Pages technologies. These technologies make it possible to develop web applications using Java.

 

Time for action – installing Jetty


Steps to make Eclipse a Jetty-ready IDE are as follows:

  1. Go to Help | Eclipse Marketplace… in Eclipse.

  2. Type Run Jetty Run in the Find field inside the Search tab and press Enter.

  3. Click on the Install button besides the Run Jetty Run plugin.

  4. Make sure Run Jetty Run is checked and click on Next.

  5. Accept the license agreement and click on Finish.

  6. The installation process can take some minutes. You will be prompted to accept installing software that contains unsigned content. Click on OK when asked to and let Eclipse continue with the installation.

  7. Once Eclipse finishes installing the plugin, it will ask you if you want to restart the IDE. Do it again.

What just happened?

We've successfully downloaded and installed our own Jetty server.

Now we are ready to create and deploy our first Vaadin-powered application.

Creating a new Vaadin project in Eclipse

The Vaadin plugin for Eclipse includes a wizard to easily create new Vaadin projects.

 

Time for action – creating a new Vaadin project


Steps to create a Vaadin application are as follows:

  1. Navigate to File | New | Other….

  2. Go to the Vaadin sub tree and select Vaadin 7 Project.

  3. Click on Next.

  4. Type welcome for your project name and select the latest Vaadin version.

    Note

    At the time of writing this book, the latest available version was 7.0.0.

  5. Click on Finish to let Eclipse create the project for us.

What just happened?

A new project has been created and we can deploy it to our server right away, so let's do it now!

Deploying and running Vaadin applications in Eclipse

Till now we have seen how to create a project, now we will see how to deploy and run the project. We are ready to see our application up and running.

 

Time for action – deploying and running


Steps to deploy and run a Vaadin application are as follows:

  1. Click on the Debug As… button on the toolbar and go to Debug As | Run Jetty.

  2. Alternatively, you can right click on your project and select Debug As | Run Jetty.

  3. Using your preferred browser, go to http://localhost:8080/welcome and play with the just created Vaadin application.

What just happened?

We have created, deployed, and run a Vaadin application using Eclipse. Upcoming applications will be generated way faster because we won't need to install any more plugins.

 

Creating and running Vaadin applications in NetBeans


You can completely skip this section if you don't want to use NetBeans to develop Vaadin applications. Stay tuned otherwise.

Installing NetBeans

NetBeans is an open source IDE similar to Eclipse, which allows developers to create web applications using Java.

 

Time for action – downloading and installing NetBeans


Installing NetBeans is quite easy. Let's see how it's done.

  1. Go to the URL http://netbeans.org/ and download the latest (or your favorite) version of NetBeans Java EE edition.

  2. Run the just downloaded installation file.

  3. The installation program will allow you to choose whether to install Apache Tomcat or Glassfish. Although you can use most Java servers, we will use Tomcat to deploy our applications. So, make sure you check Apache Tomcat and click on Next.

  4. Accept the terms of the license agreement and click on Next.

  5. Accept the terms of the JUnit license agreement and click on Next.

  6. Select the directory you would like NetBeans to be installed to and click on Next.

  7. Select the directory you would like Tomcat to be installed to and click on Next.

  8. Click on Install to start the installation process.

  9. Once the installation process is finished, you will be prompted to contribute to the NetBeans project. If you wish to, check the corresponding option and click on Finish, otherwise just click on the Finish button.

What just happened?

As you can guess, we have installed NetBeans and we are ready to create our first Vaadin project.

Creating a new Vaadin project in NetBeans

The best and the easiest way to create Vaadin 7 projects in NetBeans is by using Maven. Fortunately, NetBeans have very good support for Maven projects. If you don't know Maven, don't worry, be happy (thanks Bobby). Follow these steps and you'll get a Vaadin application willing to be hacked right away.

 

Time for action – creating a new Vaadin project


Steps to create a new Vaadin project are as follows:

  1. Go to File | New Project… and select Project from Archetype under the Maven category. Click on Next.

  2. Type vaadin in the Search field and select vaadin-archetype-application. Click on Next.

    Note

    You can think of Maven archetypes as project wizards maintained online. Maven will take care of all JARs needed.

  3. Enter welcome as Project name and click on Finish.

    Note

    You may want to fill in the rest of the fields with your preferred values, but for this first application, defaults are just fine.

What just happened?

A new project has been created and we can deploy it to our server right away, so let's do it now!

Deploying and running Vaadin applications in NetBeans

We are ready to see our application up and running.

 

Time for action – deploying and testing


Steps for deploying and testing the Vaadin application in NetBeans are as follows:

  1. Deploying an application in NetBeans couldn't be easier. Just select your welcome project and click on that little green arrow on the toolbar:

  2. Alternatively, you can do the same using the menu Run | Run Project (Vaadin Web Application). Even faster: F6.

  3. NetBeans will prompt you to select a server. You've installed Tomcat, right? Select the Apache Tomcat server and click on OK. Note that you can deploy to any server you have registered in NetBeans, we are using Tomcat just for the purposes of this example.

  4. Once you select the server, you will see a lot of messages on the output console. This is Maven preparing your application. Be patient, this process could take a while, only the first time.

  5. Go to http://localhost:8084/welcome and play with the just created Vaadin application.

What just happened?

We have successfully created, deployed, and run a Vaadin application using NetBeans.

 

Creating and running Vaadin applications using Maven


You can completely skip this section if you don't want to use Maven to develop Vaadin applications. If you want to, and you are using NetBeans, please read the previous section if you haven't already.

Vaadin 7 Maven archetype

You are still here. Chances are that you are not using Eclipse or NetBeans. Well, actually, the easier way to get Vaadin 7 is through Maven. We are not covering how to install Maven here. If you haven't already, install Maven following the instructions given in http://maven.apache.org.

 

Time for action – creating a new Vaadin project


Steps for creating a new Vaadin project are as follows:

  1. Open a new terminal in your operating system and move to the directory you want your project to be created in.

  2. Run the command line shown as follows:

    mvn archetype:generate -DarchetypeGroupId=com.vaadin -DarchetypeArtifactId=vaadin-archetype-application -DarchetypeVersion=7.0.0 -Dpackaging=war
    
  3. Enter your preferred groupId and press Enter. For example, com.example.welcome.

  4. Enter welcome as artifactId and press Enter.

  5. Press Enter to accept the default version.

  6. Press Enter to accept the default package.

  7. Confirm that everything is OK by typing Y and press Enter.

What just happened?

If you can see the rewarding BUILD SUCCESS message, you have successfully created your first Vaadin project using Maven. You must have a new directory with all the generated files for your project.

Deploying and running Vaadin applications with Maven

Deploying to Jetty is so common that we just can't break the old tradition of using it to test our application.

 

Time for action – deploying and running


Steps for deploying and running Vaadin applications with Maven are as follows:

  1. Move to the directory that Maven created for your project. If you have specified welcome as artifactId, then move to the welcome directory.

  2. Before actually deploying the application we must compile it and package it. To do that, run the command:

    mvn package
    
  3. This will take some time, so be patient.

  4. Now we are ready. Run the command:

    mvn jetty:run
    
  5. If you haven't run this before, you will see a very verbose Maven downloading stuff.

    Tip

    Just in case if you want to break the old tradition:

    mvn tomcat:run
    
  6. Go to http://localhost:8080/welcome and play with the just created Vaadin application.

What just happened?

We have successfully created, compiled, packaged, deployed, and run a Vaadin application using Maven.

 

Generated application explained


We have completed the first step of configuring our development environment to develop and run Vaadin applications. Now let's get started with the real cool stuff: the code.

Open the file WelcomeUI.java (or MyVaadinUI.java if you are using NetBeans or Maven). You will see something like this:

package com.example.welcome;

import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

public class WelcomeUI extends UI {

  protected void init(VaadinRequest request) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);

    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
      public void buttonClick(ClickEvent event) {
        layout.addComponent(new Label("Thank you for clicking"));
      }
    });
    layout.addComponent(button);
  }
}

This is going to be like a crash course on Vaadin 7. Let's pretend that we have created the previous class starting with an empty one like the following (package and import declarations will be omitted):

public class WelcomeUI {
}

This class will be the root of all our UI components. When you create a Vaadin application, and once the user browses to the URL the application has been deployed to, a web page will be automatically generated using the logic you've implemented in a certain method of this class. Which method? One overridden from the UI class, so first, we got to extend the UI class as follows:

public class WelcomeUI extends UI {
}

And the method to override is as follows:

public class WelcomeUI extends UI {

  protected void init(VaadinRequest request) {
  }

}

Note

Where is the init method called from? A Java web application is implemented using the Servlet technology. In short, a Servlet is a class that adds functionality to a web server. You can pair URLs with your own Servlet implementations and call any code you need to fulfill the requirements for your application. You do this in the web.xml file (or using annotations). Vaadin has a custom Servlet implementation which can be configured to call your own UI class implementation. Take a look at the web.xml file and find the Vaadin Servlet (com.vaadin.server.VaadinServlet).

Because this method will be called when the user browses to the application URL, you have the chance to build the user interface here. This is done by building a components tree. It's like a hierarchy where the components are arranged. We have already created the root component for the hierarchy, our WelcomeUI class. Now we can add visual components into the root component. But let's first see graphically how the component hierarchy should look when we finish our piece work:

What we have here is a WelcomeUI having a VerticalLayout which has a Button and some Labels. VerticalLayout, what's that? Think of it as an invisible component that allows you to arrange its child components vertically on the page, one upon another. So the button is on the top, then goes the first label, then the second label, and so forth.

Ok, back to the code. Take a look at how we can add that VerticalLayout invisible thing:

public class WelcomeUI extends UI {

  protected void init(VaadinRequest request) {
    VerticalLayout layout = new VerticalLayout();
    setContent(layout);
  }

}

We've created an instance of VerticalLayout and then set it to be the content of the UI. By calling the setContent(layout) method we are saying that layout is a child of our WelcomeUI instance.

Buttons

Now we have a layout in which we can add the button and all the n labels. Let's do it for the button:

public class WelcomeUI extends UI {

  protected void init(VaadinRequest request) {
    VerticalLayout layout = new VerticalLayout();
    setContent(layout);
    
    Button button = new Button("Click Me");
    layout.addComponent(button);
  }

}

No rocket science. We create an instance of Button and add it to the layout. This means the button is a child of layout, it will be displayed inside the VerticalLayout.

At this point, if we run the application, a button will be shown but it won't produce any response when clicked. Let's change that boredom:

public class WelcomeUI extends UI {

  protected void init(VaadinRequest request) {
    VerticalLayout layout = new VerticalLayout();
    setContent(layout);
        
    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
      public void buttonClick(ClickEvent event) {
        // this will be called when button is clicked
      }
    });
    layout.addComponent(button);
  }

}

Don't be afraid, we've added five lines of code, but most of them are brackets or comments. Button has a method that allows you to add click listeners. A click listener is a class that listens to click events, that's it. Here, we are using an anonymous class (you know Java, right?):

new Button.ClickListener() {
  public void buttonClick(ClickEvent event) {
    // this will be called if button is clicked
  }
}

This class is an anonymous implementation of the Button.ClickListener interface. We are passing the just created instance to the addClickListener method in order to connect our code with the click event on the button. This kind of usage of anonymous classes is very common when developing Vaadin applications, especially in places where you need this callback behavior.

Labels

We are ready to add the logic needed to dynamically add all those labels into the layout. We have a listener defining a method that will be called each time the button is clicked. So let's add the corresponding logic in that method:

public class WelcomeUI extends UI {

  protected void init(VaadinRequest request) {
    final VerticalLayout layout = new VerticalLayout();
    setContent(layout);
        
    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
      public void buttonClick(ClickEvent event) {
        Label label = new Label("Thank you for clicking");
        layout.addComponent(label);
      }
    });
    layout.addComponent(button);
  }

}

This is similar to when we added a button to the layout. This time we're adding a label. A label allows you to show non-editable texts.

Have a go hero – display some HTML text

Label components can display text in several formats. You can display plain text (that's the default), preformatted text, and HTML text. What if you want to display the "Thank you" part of the message on the label using a bold font?

Tip

HTML for this would be:

<b>Thank you</b> for clicking.

You are one line far of doing that. Try it! Use the setContentMode method of Label and the ContentMode enumeration to display HTML messages on your page.

Layout margin

If we run the application right now, we will see a screen as shown in the following screenshot (before clicking the button several times, of course):

It looks a little tight on the page. We can add some space around the layout using the setMargin method as shown in the following code snippet:

public class WelcomeUI extends UI {

  protected void init(VaadinRequest request) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);
    
    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener() {
      public void buttonClick(ClickEvent event) {
        Label label = new Label("Thank you for clicking");
        layout.addComponent(label);
      }
    });
    layout.addComponent(button);
  }

}

Now it will appear as follows:

That's it. If you make some little refactor, you will get the original application that your IDE (or Maven) created.

 

A more interesting "hello world" application


Now that you understand the code of the generated application, let's try adding a couple of features to make it a little bit more interesting. First, that boring "Thank you" message is not very useful. What if we develop an application that generates some random funny phrases? The user enters the name of two friends or something, and the application will produce random phrases about them.

Text fields

Text fields are the components we need to allow the user to enter the two names. Do you remember how we added the Click Me button? Adding text fields is the same story.

 

Time for action – using text fields


Follow these steps to add some fun to our application:

  1. Change your code to add the required text fields just before the line that creates the button instance by adding the highlighted code:

    // ...
    setContent(layout);
            
    final TextField name1 = new TextField("Somebody's name");
    final TextField name2 = new TextField("somebody's name");
    layout.addComponent(name1);
    layout.addComponent(name2);
            
    Button button = new Button("Click Me");
    // ...
  2. Add the business logic in a new method like this:

    public String getFunnyPhrase(String name1, String name2) {
      String[] verbs = new String[] {
        "eats", "melts", "breaks", "washes", "sells"};
    
      String[] bodyParts = new String[] {
        "head", "hands", "waist", "eyes", "elbows"};
    
      return name1 + " " +verbs[(int) (Math.random() * 100 % verbs.length)] + " " +name2 + "'s " +bodyParts[(int) (Math.random() * 100 % verbs.length)];
    }
  3. Change the listener to display the message returned by the business method:

    public void buttonClick(ClickEvent event) {
      String phrase = getFunnyPhrase(
          name1.getValue(), name2.getValue());
      layout.addComponent(new Label(phrase));
    }

What just happened?

We added a couple of text fields to our layout and then implemented a method to get the message to be shown on the labels. As you may have already guessed, the TextField class defines a getValue() method which returns the value which the user has introduced in the field. In this case, it happens to be a String. All input components (that is, components that get input from a user) have a getValue() method, which we can use to know the values introduced on the user interface. The following is a screenshot of the application (it seems that Maria doesn't like Juan too much):

Notifications

Notifications are a common feature in applications. You might need to notify that some event has occurred in your system when the user performs certain action. For example, in a CRUD (create, read, update, and delete) interface, your application should notify the user whether each action has been successfully executed or not.

Vaadin makes it easy for you to show fancy notifications in your web applications. The Notification class has several static methods you can call from any part of your code to show notifications. For simple notifications you can make a call such as:

Notification.show("User created");

This will display a message centered on the page shown as follows:

The message will disappear when the user moves the mouse or presses any key.

Have a go hero – show notifications

In the funny phrases application, it would be nice if the application alerts the user when no names are given instead of showing no-sense phrases. Would you be able to modify the application in order to make it show this alert using the Notification class? Try it!

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Pop quiz – Vaadin fundamentals

There are a couple of concepts you must keep in mind to be proficient with Vaadin. Answer the following questions and test yourself about your current Vaadin level.

Q1. Which method will be automatically called when somebody browses to your application URL?

  1. UI.setContent(Component component).

  2. UI.init(VaadinRequest request).

  3. VerticalLayout.init(VaadinRequest request).

  4. VerticalLayout.addComponent(Component component).

Q2. Suppose you are overriding the init method of your own UI class. How would you set the root of your components tree?

  1. By calling the setContent method of the UI class and passing the root component.

  2. By calling the addComponent method of the UI class and passing the root component.

  3. Actually, an instance of the UI class I'm writing will be the root of the tree.

  4. There's no such a thing as a components tree (it seems the book's author is going crazy).

 

Summary


We learned some cool features in this chapter:

  • We configured our development environment using Eclipse, NetBeans, and Maven.

  • We learned the details of the code IDE wizards (or Maven) generated when we create a new project.

  • We learned how components are internally arranged in a tree, where the root is a class extending UI.

  • We learned that the init method of our UI class is like a starting point for building our user interface.

  • We used labels and buttons and attached them to a vertical layout.

  • We also learned how easy it is to show notifications using the static methods of the Notification class.

Now you are able to develop simple web applications using Vaadin. The next chapter will teach you how to use more complex input components.

About the Author

  • Alejandro Duarte

    Alejandro Duarte is a developer advocate and trainer at Vaadin Ltd. He is also the author of Vaadin 7 UI Design by Example: Beginner's Guide (Packt, 2013). Graduating from the National University of Colombia with a B.S. in computer science, Alejandro learned how to program with the BASIC programming language at age 13 and has worked on many software development projects in startup-like and big companies in several countries. When he isn't coding, he splits his time between his family, his beautiful girlfriend, and his passion for the electric guitar. You can follow him on Twitter at @alejandro_du.

    Browse publications by this author

Latest Reviews

(3 reviews total)
Contenuti del libro ottimi. Utilissimo.
The book is good and in general the books of packt are good technical books. A lot of examples and very good approach to problem solving,
Le contenu de ce livre est couvert par Learning Vaadin 7 et Vaadin 7 Cookbook, qui ont par ailleurs l'avantage d'être plus complets et d'expliquer davantage.
Book Title
Access this book and the full library for FREE
Access now