Building Vaadin UI with Xtend

Today I have decided to say hello to Xtend . I had wish to learn some new programming language. The list of the criteria for choosing one, wasn’t so big .

  • It must be a programming language running on JVM,
  • and it would be nice if i don’t need to learn completely new eco system for building application.

I have checked a few options. The list of programming language for JVM is quit big, but at I was deciding between the following ones: Groovy, Scala and Xtend. At and i have choose Xtend.
 
 
Scala did not fit well in my criteria, on the other hand groovy fits my criteria but it will be the next programming language which i will learn, after Xtend. It is hard to explain why I choose Xtend. I don’t even think that the Xtend is a programming language, it’s more like extension, but it’s my opinion.

What is Xtend

So here is a few words about the language. For more info go on the Xtend web page. It’s nice and simple language which modernize Java. Instead of compiled byte code, Xtend is translated in to pretty-printed Java class, which makes it suitable for working with platforms which don’t work with byte code like GWT. The code written in Xtend produce Java classes, as i already mention, so there is no limitation in usage of any existing Java framework. The language is created with Xtext so it comes with already prepared Eclipse, and there are maven plugins for the language, so using it out of Eclipse will not be a problem.

Learning

Learning Xtend is not hard. There is a few syntax changes and few new semantics concepts which are currently missing in Java. There is nothing revolutionary comparing to the other programming language, Xtend just extends Java with the new feature which will allow you to create nicer,shorter classes. The features which get most of my attention were closure, lambda expression and extensions. Those stuff allow you to create a really nice builder classes. You can easily create UI Builders API, which will allow you to create simpler view(not in context of functionality, but in context of understanding of code).

Engaging Xtend

I’ve already mentioned that Xtend is build with Xtext, and that means that eclipse is already able to correctly handle Xtend language. After creating new Xtend class eclipse will complain about missing libs and offer you to add them in the class path, if you do not use maven for getting dependencies. The goals of this blog post are to show how Xtend can improve the way of building UI I’ve found nice examples for JavaFX, GWT … but I didn’t find anything for Vaadin, so I have decide to build a simple class for building Vaadin UI. Or to be more precise just a segment of it. The following example is not fully implemented and it can build just some part of UI, but it can be easily extend.

Vaadins UI is example of imperative UI written in the Java. Process of building UI is similar to the building imperative UI in GWT or SWT. Here is the simple example how it looks like:

package org.pis.web.application;
 
import org.eclipse.xtext.xbase.lib.InputOutput;
 
import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Window;
 
@SuppressWarnings("serial")
public class MainWindow extends Application {
 public void init() {
  Window main =  new Window();
  HorizontalLayout hl = new HorizontalLayout();
  Panel panel  = new Panel();
   
  final Button button = new Button("First button");
  button.addListener( new ClickListener() {
    
   @Override
   public void buttonClick(ClickEvent event) {
    sayHello("Hello First Button");
    button.setCaption("First button clicked");
   }
  });
   
  panel.addComponent(button);
   
  Button button2 = new Button("Second button");
  button2.addListener(new ClickListener() {
    
   @Override
   public void buttonClick(ClickEvent event) {
    sayHello("Hello Second Button");
   }
  });
   
  main.addComponent(hl);
  setMainWindow(main);
 }
 
 public void sayHello(final String string) {
  InputOutput.<String> println(string);
 }
}

The example above is typical implementation of Vaadin UI, and my goal is to make it easier and more readable. To do that I will start with the builder class.

Making UI Builder API

For getting nicer way for creating UI, I will create a component builder first. This is not a standard implementation of builder pattern, like we can do in pure Java. Actually we are building extension class. This class contains extension methods which will extend existing class with new methods. And here is implementation of the class.

package org.pis.web.application
 
import com.vaadin.ui.Window
import com.vaadin.ui.Button
import com.vaadin.ui.Panel
import com.vaadin.ui.HorizontalLayout
import com.vaadin.ui.ComponentContainer
 
class ComponentBuilder{
  
 def window ( (Window) => void initializer){
  new Window().init(initializer)
 }
  
 def panel( ComponentContainer it, (Panel) => void initializer){
  val panel = new Panel().init(initializer)
  it.addComponent(panel)
  return panel
 }
  
 def horizontalLayout (ComponentContainer it, (HorizontalLayout) => void initializer){
  val hl = new HorizontalLayout().init(initializer)
  it.addComponent(hl);
  return hl
 }
  
 def button ( ComponentContainer it, (Button)=> void initializer){
  println('Button in panel creation')
  val that = new Button().init(initializer);
  it.addComponent(that);
  return that
 }
  
 def private <T> T init(T obj, (T) => void init){
  init?.apply(obj)
  return obj 
 }
  
}

The builder class alone can not do so much, it has basic functionality like building window, adding the different kinds of panels and button, and if you are familiar with Vaadin you know that there is a lot more components built in the framework. Almost all methods in the builder have two parameters. First parameter represent container class which will handle new component, and second parameter is closure which will contain code for the component initialization.

Making UI

The code, in the following snippet, is illustration of using builder class for building a Vaadin UI. The first line, in the class body, include ComponentBuilder as an extension. And powerful Xtend’s lambda syntax allows that the code looks more simple and easier to understand. This way we eliminated Java’s inner class and lot of boilerplate code which we would have in the case of pure Java. More about Xtend lambda expressions can be found in Xtend’s documentation

package org.pis.web.application
 
import com.vaadin.Application
import com.vaadin.ui.Button
 
class MainWindowXtend extends Application{
 
    extension ComponentBuilder = new ComponentBuilder
 
    override init() {  
          mainWindow = window[
                          horizontalLayout[
                                  panel[
                                        button[
                                               caption = "First button"
                                               it.addListener()[
                                                   sayHello('Hello First Button');
                                                   component as Button
                                                   component.caption = 'First button clicked'
                                              ]
                                        ]
                                        button[
                                               caption = "Second button"
                                               it.addListener()[
                                                   sayHello('Hello');
                                              ]
                                        ]
                                 ]
                          ]
                   ];  
     }
 
     def void sayHello(String string) { 
          println(string)
     }
 
}

Conclusion

So this is really nice language, learning process take just few hours. Documentation is well written, the main language concept is shown in about 50 pages. After few hours you are ready for improving you application. This is something how Java should look like. In short, playing with Xtend was fun and it is worth of investing time.
 

Reference: Building Vaadin UI with Xtend from our JCG partner Igor Madjeric at the Igor Madjeric blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Building Vaadin UI with Xtend"

  1. Tania says:

    Hello Florian,

    My name is Tania and I work for Packt Publishing, a U.K. based publishing firm specializing in focused IT books. You can read more about us here: http://www.packtpub.com

    I came across your blog via a Google search and noticed a good amount of relevant information and blog updates related to Web development and Vaadin.

    I would like to inform you that Packt has recently published a new book Vaadin 7 UI Design By Example: Beginner’s Guide. Vaadin 7 UI Design By Example: Beginner’s Guide is an engaging guide that teaches the user how to develop web applications in minutes. With this book, the user will be able to develop useful applications and learn basics of Java web development.

    You may read more about the book here: http://www.packtpub.com/vaadin-7-user-interface-example-beginners-guide/book

    We are currently looking for experts to review this book. In case you’d like to review it. Please feel free to contact me.

    Have a nice day!

Leave a Reply


+ seven = 15



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books