Part 2 – Building a web application

Easy Swing to Web with Vaadin

Matti Tahvonen
Abstract image via Shutterstock

In the second part of this series on web apps with Vaadin, Matti Tahvonen shows us how to use Vaadin’s Swing-like components to develop web applications.

In the first part of the article series, we discussed pretty generic differences between server side web applications and applet or desktop apps that execute a substantial amount of logic in a JVM executed in the client computer. There are some largish fundamental differences that all developers moving from desktop world to web should figure out.

On the other hand, if you are an experienced Swing developer and now starting your web strategy with Vaadin, the basic component usage is something where you’ll really find yourself comfortable from the day one. The APIs are not exactly the same, but they share the principles. Let’s look at a very basic example – we’re going to create a textfield and a button and just throw the text field value on a button click to System.out for debugging.

final JTextField textField = new JTextField();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println('You typed: ' + textField.getText());

… and the very same thing in Vaadin application looks like this:

final TextField textField = new TextField();
Button button = new Button();
button.addClickListener(new Button.ClickListener() {
    public void buttonClick(Button.ClickEvent event) {
        System.out.println('You typed: ' + textField.getValue());

No need to explain what happens in either case ;-) Typically when a Swing developer starts using Vaadin, in basic component usage they find the methods they are looking for quickly with the help of their favorite IDE.

Vaadin Sampler is a demo application that contains examples of the core components with source code usage example and references to JavaDocs. It is the favourite reference for many Vaadin developers. Naturally you can also refer to plain JavaDocs and the Book of Vaadin reference manual.

Event handling and Event dispatching thread

Like most typical desktop GUI libraries, Swing serializes all access to UI via so called event dispatching thread. It fires event listeners you hook to components and if you wish to modify the UI from another thread, you submit tasks that modify your UI to it with SwingUtilities.invokeAndWait(Runnable) or SwingUtilities.invokeLater(Runnable).

In Vaadin there is no similar thread, but naturally parallel UI access needs to be avoided. Vaadin uses UI (~ browser tab/window) level locking. Like with Swing apps, the code executed by framework (UI init, event listeners) is “thread safe”” by default. These code blocks are usually run in Servlet containers thread that is handling an HTTP/Websocket request. In case you need to modify a UI from any other thread, you should use UI.getCurrent().access(Runnable) or UI.getCurrent().accessSynchronously(Runnable) to ensure there is no parallel access.

Application bootstrap

A Vaadin application is basically an HttpServlet behind the scenes. In portal environment it is a Portlet. Bootstrapping a Vaadin application depends a bit on the execution environment and the helper libraries that you use.

In Swing applications your execution typically starts from the iconic main method or from an Applet’s init method. In simple Vaadin Servlet deployment the similar entry point to your code is UI class and its init method. The counterpart for the UI class on the client side is a browser window or a browser tab. If your Vaadin application is “embedded” into another HTML page, you should consider it as the “slot” in that host page. One servlet can handle multiple UIs, mapped to different URLs, but typically you just have one per application.

A code snippet below is an example of a low level hello world Vaadin application bootstrap. It introduces a Vaadin servlet as a nested class using the @WebServlet annotation and a Vaadin UI mapped to it:

public class MyUI extends UI {

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

    protected void init(VaadinRequest vaadinRequest) {
        setContent(new Label('Hello World!'));


But, like with non-trivial Swing apps, you might want to delegate some of this low level stuff to a framework that takes care of servlet, setup and UI mapping. It is highly suggested to use either Java EE environment with Vaadin CDI add-on or Spring as a basis for your application. In these cases you typically end up having different application views as class files and container specific annotations to hint how those should be served for the end users. In the example we are using cdi-helpers add-on that also gives you a basic top level navigation and application layout for free.

The following class will be automatically visible in our applications menu. Note that the screenshot also shows some other views but our “about view”.

public class AboutView extends VerticalLayout implements View {

    void init() {
        addComponent(new Label('Hello World !'));

    public void enter(ViewChangeListener.ViewChangeEvent viewChangeEvent) {
hello world view

Screenshot of the hello world view

Laying out components

In Swing you are using different Layout implementations that take care of positioning components in JPanel’s sub classes. You will find a similarly named Layout interface in Vaadin as well, but there is a conceptual difference. In Vaadin an implementation of a Layout interface is just a normal component whose main feature is to contain other components.

Layouts in Vaadin

As you probably have learned while working with Swing applications, building layouts is generally a rather complex topic. We believe we have come up with really powerful and logical API, but understanding the basic concepts about layouts is something you really want to do before building any non-trivial application. Check out the tutorial style webinar we had last year and also refer to our manual.

Most commonly used Layout implementations are VerticalLayout, HorizontalLayout and GridLayout. By combining and configuring them intelligently you can achieve pretty much everything. CssLayout is also commonly used, due to its simplicity in browsers DOM. If you plan to theme your application heavily, it will be the favorite layout of your CSS artist, but it works also without any CSS at all, pretty much like a FlowLayout in Swing, although you do need to a tiny bit of CSS if you want the flow to be horizontal.

One thing related to Layouts is that each component in Vaadin has a caption and an icon. Most often these properties are handled by the Layout implementation and different implementations handle them in different ways. For example the FormLayout places caption and icon on the left side of the component as where HorizontalLayout and VerticalLayout place captions above the component. Naturally you don’t need to use the built in captions (and icons), but you can use Label components instead, like with Swing applications, and manually place them to the desired location.

To get an overview of Layout components in Vaadin, you can also take a quick overview of them via our Sampler application.

Custom layouts

The fact that Layout is just a component that contains other components gives us some nice flexibility. They can easily be reused to make a more domain specific classes using composition and, in case you can also master some browser development, it is easy to build completely new layouts. Even if you want to stick on the safe JVM side, the Directory contains lots of different kind of layout implementations for custom purposes. Check e.g. BorderLayout (you can probably guess how it works ;-) ), ColumnLayout, DragAndDropLayouts, PortalLayouts and the handy layout helpers in Viritin.

There is also a CustomLayout component in the core distribution, for which a better describing name would probably be “HtmlTemplateLayout”. From that you can figure out what it does. If you have a skilled “designer” in your team who masters html and css, you can use his HTML templates. Into the markup you just need to specify the “slots” where you want to place Vaadin components.

Visual view composition

Some Swing developers swear for the name of handwritten layouts and complete control of your views. Another tribe likes to draft the UIs with visual tools and then wire it to the application logic using Java. The same thing in Vaadin world.

vaadin eclipse

Vaadin Eclipse plugin comes with Vaadin Designer that lets you design your UIs in “WYSIWYG” manner. You can add code manually to your visually designed classes and then later return to visual positioning if you want.

The latest version changed the “master data” of the layout to be based on HTML5 style markup. This may sound like a weird decision for some experienced Java developers, but the idea is that your layout designs and visual appearance can also be edited by less technical graphical artists, who don’t know anything about Java programming, but can do amazing tricks with graphics, HTML, CSS and typography. Named components will naturally be available for Java developers via auto-generated classes, so customization and wiring to other parts of your application will still be plain old Java development that you already master. It is just the auto-generated Java parts that we changed into markup like format.

Part III of this series will appear on next week. You can read part I here.

Matti Tahvonen
Matti Tahvonen has a long history in Vaadin R&D: developing the core framework from the dark ages of pure JS client side to the GWT era and creating number of official and unofficial Vaadin add-ons. His current responsibility is to keep you up to date with latest and greatest Vaadin related technologies.

Inline Feedbacks
View all comments