Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Vaadin 7 UI Design By Example: Beginner's Guide
Vaadin 7 UI Design By Example: Beginner's Guide

Vaadin 7 UI Design By Example: Beginner's Guide: Do it all with Java! All you need is Vaadin and this book which shows you how to develop web applications in a totally hands-on approach. By the end of it you'll have acquired the knack and taken a fun journey on the way.

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Vaadin 7 UI Design By Example: Beginner's Guide

Chapter 2. Using Input Components and Forms – Time to Listen to Users

You must be feeling eager to get more of Vaadin. What if we take a look at some of the input components Vaadin has to offer? In this chapter, we will take a closer look at the main components for retrieving and processing all the data that users want your application to be aware of. Read this chapter and you will be able to develop a lot of new useful rich Internet applications using Vaadin.

This chapter will cover the following topics:

  • Separating business classes from UI classes

  • Responding to value changes in input components

  • Getting and setting the value of input components

  • Tooltips and error indicators

  • Underlying Vaadin technologies

  • UI components hierarchy

  • Vaadin's data model

  • Comboboxes, checkboxes, text areas, option groups, twin column selects, and date/time pickers

  • File uploading

It's time to have some fun. Keep reading.

The Time It application


A couple of years ago I was working with some friends on a personal Java project. We used to meet every Saturday to review what we had done before building the entire system. Let me introduce you to my friends: Susan Obstinate and Mark Nowsitall (weird last names, aren't they?).

"I've spent the entire week writing this code, but it's ready now," said Susan with an embittered tone.

"Let me see how you handled that," replied Mark suspiciously. Though they didn't seem to be, they were a couple.

So Susan proudly showed us her piece of code:

// some nasty code was here (censored for respect of the reader)
public String getUglyUrl(long total) {
    String url = "http://localhost/app/someservice?code=";
    
    for(long i = 0; i < total; i++) {
        url += someTrickyMath(i);
    }
    
    return url;
}

public String someTrickyMath(long i) {
    // (censored)
}

"We can use an int object type instead of long for the loop in your getUglyUrl method," instantly affirmed Mark...

Time for action – separating business classes from UI classes


Vaadin is mostly about UI. Vaadin's motto thinking of U and I is not in vain. I said mostly because you can additionally find a bunch of useful add-ons to deal with server-side technologies. Even Vaadin itself ships with some data components.

Note

There are lots of integration add-ons for Vaadin. For instance, you can integrate with technologies such as Groovy, Spring Framework, SQL, JPA, Hibernate, Lucene, Google App Engine Datastore, Quartz, JasperReports, JFreeChart, OpenLayers, Google Maps, OpenID, and even Twitter! All this with one hand tied behind your back. Visit https://vaadin.com/directory.

Most, if not all, applications have some kind of business logic. That is, something to do with the application's data. If you are an experienced developer you will agree with me that separating business logic from UI logic makes a lot of sense. For the "Time It" application, we will use two Java packages to separate business logic from...

Time for action – adding components as class members


To add UI components as class members, edit your TimeItUI class by adding these variables to it:

private static final TestSet[] testSets = new TestSet[] {
  new LongVsInt(),
  new StringVsStringBuffer(),
  new ShortCircuitVsNoShortCircuit()
};

private VerticalLayout layout = new VerticalLayout();
private ComboBox combo = new ComboBox("Test");
private final TextField textField = new TextField("Number of
                                    iterations", "1000");
private CheckBox checkBox = new CheckBox("Keep previous results");
private Button button = new Button("Time it!");
private VerticalLayout resultsLayout = new VerticalLayout();

What just happened?

The first thing you see, testSets, is just an array of business objects, specifically, an array containing instances of TestSet (take a look at the TestSet interface in the book's source code). Think of TestSet as a single scenario from which we want to obtain timing results. For example, the...

Time for action – adding some infrastructure


Edit the init method of your TimeItUI class to match the following:

@Override
protected void init(VaadinRequest request) {
  initCombo();
  initButton();
  initLayout();
}

What just happened?

Here we are breaking up the functionality to initialize our UI components in a more suitable way by implementing smaller methods. Now that we have the required infrastructure, we can start adding input components.

Comboboxes

A combobox is an input component that allows users to select an option from a drop-down list. It looks like the following screenshot:

You must be thinking "yeah right, but how do you put those options in there?" This is easy:

ComboBox c = new ComboBox("Select an option");
c.addItem("Option one");
c.addItem("Option two");
c.addItem("Option three");

If you have the options in a Java Collection class, you can pass the Collection instance to the constructor like this:

ArrayList<String> options = new ArrayList<>();
options.add("Option...

Time for action – adding a combobox


Implement the initCombo method of your TimeItUI class as shown in the following code snippet:

private void initCombo() {
  for(TestSet testSet : testSets) {
    combo.addItem(testSet);
    combo.setItemCaption(testSet, testSet.getTitle());
  }
  
  combo.addValueChangeListener(new ValueChangeListener() {
    @Override
    public void valueChange(ValueChangeEvent event) {
      TestSet testSet = (TestSet) combo.getValue();
      textField.setValue("" + testSet.getDefaultTimes());
      button.setDescription(testSet.getDescription());
    }
  });
  
  combo.setImmediate(true);
}

What just happened?

It's not that complicated. If we isolate the for portion of the previous code, we'll get this:

for(TestSet testSet : testSets) {
  combo.addItem(testSet);
  combo.setItemCaption(testSet, testSet.getTitle());
}

For each TestSet instance in our array, we add a TestSet instance and then we say, "Okay, Vaadin for this testSet array I just added, please show what testSet...

Time for action – validating user input


We can run a TestSet instance only if the user selects one. Follow these steps to add a proper validation:

  1. Implement your initButton method to match this code:

    private void initButton() {
      button.addClickListener(new ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
          if(isValid()) {
            runSelectedTest();
          }
        }
      });
    }
  2. Now implement your validate method. Here is how we validate:

    public boolean isValid() {
      combo.setComponentError(null);
      textField.setComponentError(null);
      
      boolean isValid = true;
      
      if(combo.getValue() == null) {
        combo.setComponentError(
            new UserError("Select a test from the list."));
        isValid = false;
      }
      
      if(textField.getValue().toString().isEmpty()) {
        textField.setComponentError(new UserError(
            "You must introduce the number of iterations to execute"));
    
        isValid = false;
      }
      
      return isValid;
    }

What just happened?

For the button listener, it's...

Time for action – adding input component into the layout


Implement your initLayout method using the following snippet of code:

private void initLayout() {
  layout.setMargin(true);
  layout.setSpacing(true);
  layout.addComponent(combo);
  layout.addComponent(textField);
  layout.addComponent(checkBox);
  layout.addComponent(button);
  layout.addComponent(resultsLayout);
  
  setContent(layout);
}

What just happened?

We let the layout to have an appropriate margin and spacing. This last one adds some space between components instead of having them bonded inside the layout. Following that, we add combo, textField, checkBox, button, and a VerticalLayout component to put some labels for showing the results of the test case execution. Finally, the last statement sets layout as content of the page.

Checkboxes

Everyone knows checkboxes. Have you ever accepted license agreements during software installations? Just in case, this is a checkbox:

We have already created our checkbox:

private CheckBox checkBox...

Time for action – running the test set


Implement your runSelectedTest method. This method will be called when the user presses the Time it! button:

public void runSelectedTest() {
  Long times = Long.parseLong(textField.getValue());
  Collection<String> results = TestSetExecutor.execute(
      (TestSet) combo.getValue(), times);
  showResults(results);
}

What just happened?

Here, we're converting the string stored in the text field to a Long number using Long.parseLong (a potential exception, NumberFormatException, pokes its head).

Once we have the Long value, we execute the results using a helper class in the biz package (TestSetExecutor). This helper class has an execute method that expects the TestSet to execute and the number of iterations to perform for each test in the TestSet. The execute method returns all the results as a collection of strings that we can proudly show to the user. As proudly as Susan when she presented her code.

Have a go hero – add a validation to Time It

When...

Time for action – showing the results


The default behavior of the application is to show only the results of the last execution. We need to remove all the results that have been previously added to the resultsLayout component if the user has not checked Keep previous results. To do that, implement your showResults method:

private void showResults(Collection<String> results) {
  if(!checkBox.getValue()) {
    resultsLayout.removeAllComponents();
    
  } else if(resultsLayout.getComponentCount() > 0) {
    resultsLayout.addComponent(new Label("--"));
  }
  
  for(String result : results) {
    resultsLayout.addComponent(new Label(result));
  }
}

What just happened?

If the checkbox is not checked, we can remove all the components in resultsLayout (not in layout, we don't want baffled users here):

resultsLayout.removeAllComponents();

If we don't have to remove previous results, we add a separator and iterate over the results to add each one using a label.

Tip

You can remove single components...

Thinking in Vaadin


Your brain must have started to feel comfortable using UI components such as labels, text fields, comboboxes, buttons, vertical layouts, and notifications. You know how to respond to events on these components by implementing click listeners and value change listeners. You can get the introduced (or selected) values from input components, and you can wire all this up inside a custom class extending Vaadin's UI.

The rest of the trip in this book is about learning more components, how to respond to events on components, and how to make them look as we want them to look. To prepare your brain for this trip, we will right now cover some basic theory about Vaadin. So relax, close your IDE for a little while, and let your fingers have a rest while we learn some nuts and bolts of Vaadin.

Servlets and GWT

How can Vaadin render all those nice widgets on the browser using only an instance of a class (the one that extends UI)? Let's expose Vaadin's magic.

We can easily think of the browser...

Time for action – binding data to properties


There's no better way to learn than practice. Follow these steps to see how binding works in real life:

  1. Create a new project named binding using your IDE. A Vaadin one, of course.

  2. Don't hesitate and delete all the content in the generated BindingUI class.

  3. Create a new local instance of TextField and turn immediate mode on:

      @Override
      protected void init(VaadinRequest request) {
        TextField textField = new TextField("Data");
        textField.setImmediate(true);
      }
  4. Create a new local instance of Label:

        Label label = new Label();
  5. Add the TextField and Label components to a new VerticalLayout and set it to be the content of the UI:

    VerticalLayout layout = new VerticalLayout();
    layout.addComponent(textField);
    layout.addComponent(label);
    setContent(layout);
  6. Nothing new so far, so create a new instance of the ObjectProperty class:

    ObjectProperty<String> property =
                         new ObjectProperty<String>("the value");
  7. Wow, that was new...

More input components


It's time to continue with our trip. Vaadin has several built-in input components (or fields as they implement directly or indirectly the Field interface). All these components extend from AbstractField or AbstractSelect. Let's take a look at some of them.

Text area

TextArea is quite similar to TextField. The difference is that the user can enter multiline texts. Take a look at this sample application:

public class TextareaUI extends UI implements ValueChangeListener {

  @Override
  protected void init(VaadinRequest request) {
    // our TextArea component
    TextArea textArea = new TextArea(
        "Enter some multi-lined text and press TAB:");
    textArea.addValueChangeListener(this);
    textArea.setImmediate(true);

    VerticalLayout layout = new VerticalLayout();
    layout.addComponent(textArea);
    setContent(layout);
  }

  @Override
  public void valueChange(ValueChangeEvent event) {
    String userText = event.getProperty().getValue()
        .toString...

Time for action – fixing the OptionGroup example


It's time for our good deed of the day. OptionGroup has a very simple method to turn on a multiple selection mode: setMultiSelect.

  1. Open or import the optiongroup example in your IDE.

  2. Add og.setMultiSelect(true) after instantiating og.

  3. Deploy and run the example.

What just happened?

Take a look at the new interface:

As you can see, now the component is displayed as an assortment of checkboxes and the getValue method (of both OptionGroup and Property) returns a Java Collection (actually a Set). This happens when we activate multiselect mode.

Note

We are not talking about Java EE, but just in case, the correct answers are:

Session beans and Message-driven beans

Have a go hero – improve the OptionGroup example

Try changing the OptionGroup example application to show a message informing whether the answer is correct or not. Here is a quick hint: cast the value to a Java Set instance.

Twin column selects

Instead of the OptionGroup component we can use TwinColSelect...

Time for action – using an InlineDateField component


Let's change the DateField example a little bit:

  1. Open or import the datefield example in your IDE.

  2. Replace DateField with InlineDateField in DateFieldUI.java.

  3. Deploy and run the example.

What just happened?

This is the result you get:

You cannot type the year now, you have to select it from the component.

Uploading files

Study this simple example that displays (in the console) the content of a text file uploaded by the user:

public class UploadUI extends UI implements Receiver {
  @Override
  protected void init(VaadinRequest request) {
    Upload upload = new Upload(
        "Select a text file and look at the console",
        this);

    VerticalLayout layout = new VerticalLayout();
    layout.addComponent(upload);
    setContent(layout);
  }

  @Override
  public OutputStream receiveUpload(String filename,
      String mimeType) {
    return new OutputStream() {
      @Override
      public void write(int b) throws IOException {
        System...

Summary


This was a big chapter. Look at what we have covered:

  • We learned how to create Vaadin applications that communicate with business classes.

  • We took a look at the underlying technologies that make it possible to write web applications entirely in Java.

  • We got to know the Vaadin data model and its core concepts: properties, items, and containers.

  • We saw a simplified version of the UI components hierarchy.

  • We learned the common functionality for UI components and we saw that this functionality is defined in the Component interface paired with the AbstractComponent class.

  • We have learned how to use most of the input components available in Vaadin.

So far, our applications have had a boring layout (VerticalLayout). In the next chapter we will start making more appealing applications by learning a lot about layouts in Vaadin. See you there.

Left arrow icon Right arrow icon

Key benefits

  • Learn how to develop Vaadin web applications while having fun and getting your hands dirty
  • Develop relevant and unique applications following step-by-step guides with the help of plenty of screenshots from the start
  • The best available introduction to Vaadin with a practical hands-on approach and easy to read tutorials and examples

Description

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.

Who is this book for?

If you have experience with the Java language and want to create web applications that look good without having to deal with HTML, XML, and JavaScript, this book is for you. Basic Java programming skills are required, but no web development knowledge is needed at all.

What you will learn

  • Create Vaadin applications using Eclipse, Netbeans, and Maven
  • Use input components such as text fields, buttons, combo boxes, check boxes, and more
  • Use layouts, panels, and windows to arrange UI components
  • Incorporate navigation capabilities to Vaadin applications
  • Use tables and trees to present complex data
  • Use advanced components such as progress indicators, context menus, sliders, and drag-and-drop capabilities
  • Include custom HTML, Flash, and other web content in Vaadin applications
  • Customize UI components by using CSS
  • Develop your own components

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 26, 2013
Length: 246 pages
Edition : 1st
Language : English
ISBN-13 : 9781782162278
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 26, 2013
Length: 246 pages
Edition : 1st
Language : English
ISBN-13 : 9781782162278
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 83.98
Vaadin 7 UI Design By Example: Beginner's Guide
€41.99
Vaadin 7 Cookbook
€41.99
Total 83.98 Stars icon
Banner background image

Table of Contents

8 Chapters
Writing Your First Vaadin-powered Application Chevron down icon Chevron up icon
Using Input Components and Forms – Time to Listen to Users Chevron down icon Chevron up icon
Arranging Components into Layouts Chevron down icon Chevron up icon
Using Vaadin Navigation Capabilities Chevron down icon Chevron up icon
Using Tables – Time to Talk to Users Chevron down icon Chevron up icon
Adding More Components Chevron down icon Chevron up icon
Customizing UI Components – Time to Theme it Chevron down icon Chevron up icon
Developing Your Own Components Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(11 Ratings)
5 star 54.5%
4 star 36.4%
3 star 9.1%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Quam P-R Dec 26, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Voici un bon bouquin qui mêle pratique et théorie !!!Génial pour débutants et ceux qui connaissent Java qui ont envie d'aborder le développement Web avec un framework sans trop se prendre la tête.Excellent. Je le conseille vivement.
Amazon Verified review Amazon
JM Sep 15, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
When I started with Vaadiin 6 I was looking for a step by step guide, There are a lot of guides for do something in a blog, or in the help, but nothing like this book. A easy step by step guide, with screens, tips, comments. I really liked this book. I Just learned a lot of stuff I missed in my transition to Vaadin 7 with this book. You must have it.
Amazon Verified review Amazon
mauro@dogma Jun 21, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very useful guide to start development UI with Vaadin.Many examples guide the reader and provide tricks for start developing fast and be productive in 1 day!Thx
Amazon Verified review Amazon
Jan Krabbenbos Sep 29, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very nice introduction into this Java framework for web based applications. It gives a good introduction, but you need some experience with J2EE.
Amazon Verified review Amazon
Michael Mar 25, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Best for start, even if u dont know java. Just read before about Observer patern. Cons: no info about connection to data base.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.