Using Vaadin Grid

Last week we released one of the most important components in the 7.4 version of the framework - the Grid. If you haven’t taken a look at it yet, I can tell you that there are quite a few features that you can use to present and tune to get your data on the screen.

Like you know, Grid is now a part of the open source framework and free to use under Apache 2 license. To help you get started with it, we wanted to give you some code snippets to visualize how it’s used.

Create and show a data grid

Create an empty Grid with a caption and add it to your layout.  Here we want to reserve most of the space in VerticalLayout for the grid:

Grid grid = new Grid("My data grid");
layout.addComponent(grid);
grid.setSizeFull();
layout.setExpandRatio(grid, 1);

There are alternative constructors for binding the Container data source at the same time. Check out the Grid Javadocs for more details.

Adding data

The most simple way of adding data is to just add some rows:

grid.addRow("com.vaadin", "vaadin-server", "7.4.0");
grid.addRow("com.vaadin", "vaadin-client-compiled", "7.4.0");

You already guessed that this adds two rows with three columns to the data grid, but you can go further by binding containers as data source:

final BeanItemContainer<Person> ds = 
    new BeanItemContainer<Person>(Person.class, personList);
Grid grid = new Grid("Employees", ds);
layout.addComponent(grid);

Of course you can use other (your favorite) containers, from LazyQueryContainer, CollectionContainer to ListContainer, and your own custom ones.

Configuring columns

Now you have something to show. But maybe not all. If your Person objects have nested POJOs, they don’t look that nice, but fortunately you can easily expand those:

ds.addNestedContainerBean("address");

Setting the column order is equally as easy:

grid.setColumnOrder("firstName", "lastName", "salary",
    "address.streetAddress", "address.city", "address.country");

You can also set sizes for individual columns. Just grab the column handle and configure:

grid.getColumn("salary").setExpandRatio(1); // take all available

And you can also set the minimum width for a column:

grid.getColumn("salary").setMinimumWidth(200); // can expand

If you have too many columns to be visible at once, you can have some columns fixed so that they are kept visible all the time.

grid.setFrozenColumnCount(2);

Headers and Footers

While data is the most important thing, it is also important to make it meaningful. Good headers and titles help to bring meaning to your data.

HeaderRow row = grid.prependHeaderRow();
row.join("firstName", "lastName").setHtml("<b>Full name</b>");

As you can see, the HTML can be used to emphasize things.

And the same goes for footers. Display aggregate values, totals, averages or just some text in the end of the data grid:

FooterRow footer = grid.appendFooterRow();
footer.getCell("salary").setText("avg: 1528.55");

Custom data presentation

Sometimes custom data presentation is as easy as binding data, but most typically your data does not match the presentation you want to have. Here is what you can do:

grid.getColumn("salary").setRenderer(new ProgressBarRenderer(),
               new BigDecimalToDoubleConverter());

What happens here is that a “renderer” is used to present column values. You can use one of the built in renderers and converters, or simply create your own special converter:

grid.getColumn("busy")
    .setConverter(new BooleanTrafficLight())
    .setRenderer(new HtmlRenderer());

Notice the fluent API implementation. Here a colored dot is presented instead of the underlying boolean value.

Selecting rows

Primarily you present long (or short) lists of data with the data grid, let the user select something there and receive an event as he or she makes the selection:

grid.setSelectionMode(SelectionMode.SINGLE);
grid.addSelectionListener(new SelectionListener() {

@Override
   public void select(SelectionEvent event) {
       Notification.show("Select row: "+grid.getSelectedRow());
   }
});

You can choose from NONE, SINGLE and MULTI here and receive an event when the selection changes.

Inline editing

Using editor capabilities, you can let the users edit the data in place:

grid.setEditorEnabled(true);
grid.setEditorSaveCaption("Save my data, please!");

While this would already make the data editable, the defaults might not be enough for your data types. Then you can create your own forms:

final MyForm form = new MyForm();
layout.addComponent(form);
grid.addSelectionListener(new SelectionListener() {

    @Override
    public void select(SelectionEvent event) {
        BeanItem<Person> item = ds.getItem(grid.getSelectedRow());
        form.fieldGroup.setItemDataSource(item);
    }
});

And then create a simple form of your own - TextFields, DateFields, Sliders,... whatever you might need there. Here we use the GridLayout (just a layout, not to be confused with the Grid itself) to present a form of three columns:

public class MyForm extends GridLayout {

    public BeanFieldGroup<Person> fieldGroup =
        new BeanFieldGroup<Person>(Person.class);

    private TextField firstName, lastName, salary;

    public MyForm() {
       super(3, 1);
       setSpacing(true);
       fieldGroup.buildAndBindMemberFields(this);
       addComponents(firstName, lastName, salary);
       space();
       addComponent(new Button("Save", new ClickListener() {

           @Override
           public void buttonClick(ClickEvent event) {
               try {
                   fieldGroup.commit();
               } catch (CommitException e) {
                   //TODO: Say and do something meaningful
               }
           }
       }));

       addComponent(new Button("Cancel", new ClickListener() {

           @Override
           public void buttonClick(ClickEvent event) {
               fieldGroup.discard();
           }
       }));
   }
}

With this, you already have a data grid driven CRUD application in your hands. Enjoy Java’s benefits and refactor and rename it to your needs.

Read more

This was just a small glimpse to what Vaadin Grid has to offer. There is much more you can achieve, with styling, filtering and sorting. Take a look at the developer guide, wiki and Javadocs for more.

Visit vaadin.com/grid

Community Spotlight - February 2015

Spotlight, featured image

Directory renewal is getting closer.

In last month’s episode, we didn’t discuss about the Directory or traditional Vaadin add-ons at all. So lets start with some news about the upcoming Directory renewal. We have just deployed a new version of the preview, now with a fully featured administration console.

Add-on authors can already use it to add icons to their add-ons and spice up their descriptions and release notes with Markdown syntax. We think icons will be a great way to help people recognise their favourites and rich text formatting is a big aid for those who consider the directory page as their project’s homepage.

Although, you should note that it works with the same database as the public side. New icons will show up only in the preview version and possible markdown formatting will show up as raw text on the old side. If you find any oddities or improvement ideas, please, report them via the “Give Feedback” button on the top of the Directory preview.

JVx Application Framework generates you a Vaadin UI for web, Swing for desktop

In this article series we have referred lots of content from SibVisions’s blog that relate to Vaadin. This months highlight is definitely a nice video of a Vaadin UI controlling window shutters.

In case somebody has missed it, one of the reasons for their constant feed of Vaadin articles is their Apache 2 licenced UI toolkit called JVx Application Framework. With it you can build your UI just once and deploy it to web, mobile and desktop. JVx runs its web UI on Vaadin, its desktop UI on Swing and its mobile UI as native Android or iOS apps.

Jvx is definitely a tool to check out for those who need to maintain the same application on both web and desktop. To get a better understanding of what Jvx can do, you can check out this article and the included video that introduces their upcoming Java FX support.

BTW. Related to Swing, we are currently preparing some material for developers coming to Vaadin from a Swing background. If you have experiences you’d like to share or tips about topics we should handle, feel free to contact me via email. I’d appreciate all insights, it is way too long since I wrote my first Vaadin app to remember what I felt difficult - and I haven’t worked with Swing since.

Helper libraries like Jvx and vaadin4spring, which we discussed in the last episode, don’t fit into the Directory that well and might not get the publicity they’d deserve in Vaadin community. Thus I decided to create a new page for this kind of projects to the wiki. I created a separate category for various examples like technology integrations. I quickly filled in some projects, but there are lots of good stuff missing. Don’t hesitate to add links and short description to other projects. Lets make this a shared bookmark collection of Vaadin related OS projects.

Lots of Directory activity

Since we crossed the boundary of 500 add-ons we have had an insane activity in the Directory. Since the beginning of the year, there are 13 completely new add-ons and 43 different add-ons have celebrated new releases already during 2015. Big thanks to all active add-on contributors!

Completely new add-ons to the Directory during 2015:

Vaadin 7.4 released

Welcome to the next 7-series release. Even though this is called a "minor release", Vaadin 7.4 includes some enhancements which are actually making it a huge step forward.

The Grid - for all your data

First things first. The Table component has been one of the most prominent components in Vaadin Framework. There is virtually no business application that does not present a list of tabular data somehow, somewhere.

Vaadin Grid is the next generation of the Table component, using fast and hardware optimized scrolling to present a lot of data in grid format. Combine with inline editing, filters, sorting, custom cell rendering and style it using the Valo theme engine for your needs.

One of the interesting differences to Table is that Grid can also be used solely on the client side. Not only for offline Vaadin applications, but also separately in pure GWT applications. This is what you actually see in above sample: a client-side Vaadin Grid rendering without a backend.

Learn more about the brand new Grid at vaadin.com/grid

Declarative UI syntax

The default way to build layouts and component hierarchies in Vaadin has been programmatically, in Java. The component encapsulation brings reusability, but if you wish to have more logical encapsulation (opposed to simple layout structure encapsulation), you can easily end up in rather deep layout structures within a single Java file.

If you are a very strict programmer, you can be declarative in your layouts in pure Java language, but if you are  like me, “real” declarative UI means something like XML layout specifications. And that is exactly what Vaadin 7.4 brings us: HTML-based layout syntax

for Vaadin components.

<v-vertical-layout width="100%" spacing>
   <v-text-field caption="Name" width="100%" />
   <v-text-field caption="Email" width="100%" />
   <v-button caption="Save" />
</v-vertical-layout>

One obvious benefit is that now you can see the layout structure. Whether you have a complicated form or a fixed positioned component, this really helps you to better see what is the structure and why your layout expands like it does.

The second benefit is that declarative user interfaces are by nature more static and it is usually a good idea to keep buttons, lists and other components in the same place. It helps us to focus more on the content and less on how to use the UI.

To learn more of how to use this approach in your application, see the walk-through ‘Declarative 101’ blogpost.

Get Vaadin 7.4

If you are a Vaadin 7.3 user already, there should be no reason not to start using Vaadin 7.4 as well. Whether you try out the new declarative Design or Grid, there are a lot of other things as well, like:

  • HTML support in all component captions.

  • Field.clear() to simply clear a field value.

  • @Viewport and @ViewportGeneratorClass annotations to easily configure UIs for different browsers and screen sizes.

  • @NoLayout for RPC method or state property to avoid unnecessary layout calculations in components.


Check out the  list of enhancements and fixes  that make this release an important framework milestone.

Get Vaadin 7.4.0