5.16. Table

Because of pressing release schedules to get this edition to your hands, we were unable to completely update this section. The description of the Table component should be mostly up-to-date, but some data binding related topics still require significant revision. Please consult the web version once it is updated, or the next print edition.

The Table component is intended for presenting tabular data organized in rows and columns. The Table is one of the most versatile components in Vaadin. Table cells can include text or arbitrary UI components. You can easily implement editing of the table data, for example clicking on a cell could change it to a text field for editing.

The data contained in a Table is managed using the Data Model of Vaadin (see Chapter 9, Binding Components to Data), through the Container interface of the Table. This makes it possible to bind a table directly to a data source, such as a database query. Only the visible part of the table is loaded into the browser and moving the visible window with the scrollbar loads content from the server. While the data is being loaded, a tooltip will be displayed that shows the current range and total number of items in the table. The rows of the table are items in the container and the columns are properties. Each table row (item) is identified with an item identifier (IID), and each column (property) with a property identifier (PID).

When creating a table, you first need to define columns with addContainerProperty(). This method comes in two flavors. The simpler one takes the property ID of the column and uses it also as the caption of the column. The more complex one allows differing PID and header for the column. This may make, for example, internationalization of table headers easier, because if a PID is internationalized, the internationalization has to be used everywhere where the PID is used. The complex form of the method also allows defining an icon for the column from a resource. The "default value" parameter is used when new properties (columns) are added to the table, to fill in the missing values. (This default has no meaning in the usual case, such as below, where we add items after defining the properties.)

/* Create the table with a caption. */
Table table = new Table("This is my Table");

/* Define the names and data types of columns.
 * The "default value" parameter is meaningless here. */
table.addContainerProperty("First Name", String.class,  null);
table.addContainerProperty("Last Name",  String.class,  null);
table.addContainerProperty("Year",       Integer.class, null);

/* Add a few items in the table. */
table.addItem(new Object[] {
    "Nicolaus","Copernicus",new Integer(1473)}, new Integer(1));
table.addItem(new Object[] {
    "Tycho",   "Brahe",     new Integer(1546)}, new Integer(2));
table.addItem(new Object[] {
    "Giordano","Bruno",     new Integer(1548)}, new Integer(3));
table.addItem(new Object[] {
    "Galileo", "Galilei",   new Integer(1564)}, new Integer(4));
table.addItem(new Object[] {
    "Johannes","Kepler",    new Integer(1571)}, new Integer(5));
table.addItem(new Object[] {
    "Isaac",   "Newton",    new Integer(1643)}, new Integer(6));

In this example, we used an increasing Integer object as the Item Identifier, given as the second parameter to addItem(). The actual rows are given simply as object arrays, in the same order in which the properties were added. The objects must be of the correct class, as defined in the addContainerProperty() calls.

Figure 5.45. Basic Table Example

Basic Table Example

Scalability of the Table is largely dictated by the container. The default IndexedContainer is relatively heavy and can cause scalability problems, for example, when updating the values. Use of an optimized application-specific container is recommended. Table does not have a limit for the number of items and is just as fast with hundreds of thousands of items as with just a few. With the current implementation of scrolling, there is a limit of around 500 000 rows, depending on the browser and the pixel height of rows.

5.16.1. Selecting Items in a Table

The Table allows selecting one or more items by clicking them with the mouse. When the user selects an item, the IID of the item will be set as the property of the table and a ValueChangeEvent is triggered. To enable selection, you need to set the table selectable. You will also need to set it as immediate in most cases, as we do below, because without it, the change in the property will not be communicated immediately to the server.

The following example shows how to enable the selection of items in a Table and how to handle ValueChangeEvent events that are caused by changes in selection. You need to handle the event with the valueChange() method of the Property.ValueChangeListener interface.

// Allow selecting items from the table.
table.setSelectable(true);

// Send changes in selection immediately to server.
table.setImmediate(true);

// Shows feedback from selection.
final Label current = new Label("Selected: -");

// Handle selection change.
table.addValueChangeListener(new Property.ValueChangeListener() {
    public void valueChange(ValueChangeEvent event) {
        current.setValue("Selected: " + table.getValue());
    }
});

Figure 5.46. Table Selection Example

Table Selection Example

If the user clicks on an already selected item, the selection will deselected and the table property will have null value. You can disable this behaviour by setting setNullSelectionAllowed(false) for the table.

The selection is the value of the table's property, so you can get it with getValue(). You can get it also from a reference to the table itself. In single selection mode, the value is the item identifier of the selected item or null if no item is selected. In multiple selection mode (see below), the value is a Set of item identifiers. Notice that the set is unmodifiable, so you can not simply change it to change the selection.

Multiple Selection Mode

A table can also be in multiselect mode, where a user can select multiple items by clicking them with left mouse button while holding the Ctrl key (or Meta key) pressed. If Ctrl is not held, clicking an item will select it and other selected items are deselected. The user can select a range by selecting an item, holding the Shift key pressed, and clicking another item, in which case all the items between the two are also selected. Multiple ranges can be selected by first selecting a range, then selecting an item while holding Ctrl, and then selecting another item with both Ctrl and Shift pressed.

The multiselect mode is enabled with the setMultiSelect() method of the AbstractSelect superclass of Table. Setting table in multiselect mode does not implicitly set it as selectable, so it must be set separately.

The setMultiSelectMode() property affects the control of multiple selection: MultiSelectMode.DEFAULT is the default behaviour, which requires holding the Ctrl (or Meta) key pressed while selecting items, while in MultiSelectMode.SIMPLE holding the Ctrl key is not needed. In the simple mode, items can only be deselected by clicking them.

5.16.2. Table Features

Page Length and Scrollbar

The default style for Table provides a table with a scrollbar. The scrollbar is located at the right side of the table and becomes visible when the number of items in the table exceeds the page length, that is, the number of visible items. You can set the page length with setPageLength().

Setting the page length to zero makes all the rows in a table visible, no matter how many rows there are. Notice that this also effectively disables buffering, as all the entire table is loaded to the browser at once. Using such tables to generate reports does not scale up very well, as there is some inevitable overhead in rendering a table with Ajax. For very large reports, generating HTML directly is a more scalable solution.

Resizing Columns

You can set the width of a column programmatically from the server-side with setColumnWidth(). The column is identified by the property ID and the width is given in pixels.

The user can resize table columns by dragging the resize handle between two columns. Resizing a table column causes a ColumnResizeEvent, which you can handle with a Table.ColumnResizeListener. The table must be set in immediate mode if you want to receive the resize events immediately, which is typical.

table.addColumnResizeListener(new Table.ColumnResizeListener(){
    public void columnResize(ColumnResizeEvent event) {
        // Get the new width of the resized column
        int width = event.getCurrentWidth();
        
        // Get the property ID of the resized column
        String column = (String) event.getPropertyId();

        // Do something with the information
        table.setColumnFooter(column, String.valueOf(width) + "px");
    }
});
        
// Must be immediate to send the resize events immediately
table.setImmediate(true);

See Figure 5.47, “Resizing Columns” for a result after the columns of a table has been resized.

Figure 5.47. Resizing Columns

Resizing Columns

Reordering Columns

If setColumnReorderingAllowed(true) is set, the user can reorder table columns by dragging them with the mouse from the column header,

Collapsing Columns

When setColumnCollapsingAllowed(true) is set, the right side of the table header shows a drop-down list that allows selecting which columns are shown. Collapsing columns is different than hiding columns with setVisibleColumns(), which hides the columns completely so that they can not be made visible (uncollapsed) from the user interface.

You can collapse columns programmatically with setColumnCollapsed(). Collapsing must be enabled before collapsing columns with the method or it will throw an IllegalAccessException.

// Allow the user to collapse and uncollapse columns
table.setColumnCollapsingAllowed(true);

// Collapse this column programmatically
try {
    table.setColumnCollapsed("born", true);
} catch (IllegalAccessException e) {
    // Can't occur - collapsing was allowed above
    System.err.println("Something horrible occurred");
}
        
// Give enough width for the table to accommodate the
// initially collapsed column later
table.setWidth("250px");

See Figure 5.48, “Collapsing Columns”.

Figure 5.48. Collapsing Columns

Collapsing Columns

If the table has undefined width, it minimizes its width to fit the width of the visible columns. If some columns are initially collapsed, the width of the table may not be enough to accomodate them later, which will result in an ugly horizontal scrollbar. You should consider giving the table enough width to accomodate columns uncollapsed by the user.

Components Inside a Table

The cells of a Table can contain any user interface components, not just strings. If the rows are higher than the row height defined in the default theme, you have to define the proper row height in a custom theme.

When handling events for components inside a Table, such as for the Button in the example below, you usually need to know the item the component belongs to. Components do not themselves know about the table or the specific item in which a component is contained. Therefore, the handling method must use some other means for finding out the Item ID of the item. There are a few possibilities. Usually the easiest way is to use the setData() method to attach an arbitrary object to a component. You can subclass the component and include the identity information there. You can also simply search the entire table for the item with the component, although that solution may not be so scalable.

The example below includes table rows with a Label in XHTML formatting mode, a multiline TextField, a CheckBox, and a Button that shows as a link.

// Create a table and add a style to allow setting the row height in theme.
final Table table = new Table();
table.addStyleName("components-inside");

/* Define the names and data types of columns.
 * The "default value" parameter is meaningless here. */
table.addContainerProperty("Sum",            Label.class,     null);
table.addContainerProperty("Is Transferred", CheckBox.class,  null);
table.addContainerProperty("Comments",       TextField.class, null);
table.addContainerProperty("Details",        Button.class,    null);

/* Add a few items in the table. */
for (int i=0; i<100; i++) {
    // Create the fields for the current table row
    Label sumField = new Label(String.format(
                   "Sum is <b>$%04.2f</b><br/><i>(VAT incl.)</i>",
                   new Object[] {new Double(Math.random()*1000)}),
                               Label.CONTENT_XHTML);
    CheckBox transferredField = new CheckBox("is transferred");
    
    // Multiline text field. This required modifying the 
    // height of the table row.
    TextField commentsField = new TextField();
    commentsField.setRows(3);
    
    // The Table item identifier for the row.
    Integer itemId = new Integer(i);
    
    // Create a button and handle its click. A Button does not
    // know the item it is contained in, so we have to store the
    // item ID as user-defined data.
    Button detailsField = new Button("show details");
    detailsField.setData(itemId);
    detailsField.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            // Get the item identifier from the user-defined data.
            Integer iid = (Integer)event.getButton().getData();
            Notification.show("Link " +
                              iid.intValue() + " clicked.");
        } 
    });
    detailsField.addStyleName("link");
    
    // Create the table row.
    table.addItem(new Object[] {sumField, transferredField,
                                commentsField, detailsField},
                  itemId);
}

// Show just three rows because they are so high.
table.setPageLength(3);

The row height has to be set higher than the default with a style rule such as the following:

/* Table rows contain three-row TextField components. */
.v-table-components-inside .v-table-cell-content {
height: 54px;
}

The table will look as shown in Figure 5.49, “Components in a Table”.

Figure 5.49. Components in a Table

Components in a Table

Iterating Over a Table

As the items in a Table are not indexed, iterating over the items has to be done using an iterator. The getItemIds() method of the Container interface of Table returns a Collection of item identifiers over which you can iterate using an Iterator. For an example about iterating over a Table, please see Section 9.5, “Collecting Items in Containers”. Notice that you may not modify the Table during iteration, that is, add or remove items. Changing the data is allowed.

Filtering Table Contents

A table can be filtered if its container data source implements the Filterable interface, as the default IndexedContainer does. See Section 9.5.7, “Filterable Containers”.

5.16.3. Editing the Values in a Table

Normally, a Table simply displays the items and their fields as text. If you want to allow the user to edit the values, you can either put them inside components as we did above, or you can simply call setEditable(true) and the cells are automatically turned into editable fields.

Let us begin with a regular table with a some columns with usual Java types, namely a Date, Boolean, and a String.

// Create a table. It is by default not editable.
final Table table = new Table();

// Define the names and data types of columns.
table.addContainerProperty("Date",     Date.class,  null);
table.addContainerProperty("Work",     Boolean.class, null);
table.addContainerProperty("Comments", String.class,  null);

// Add a few items in the table.
for (int i=0; i<100; i++) {
    Calendar calendar = new GregorianCalendar(2008,0,1);
    calendar.add(Calendar.DAY_OF_YEAR, i);
    
    // Create the table row.
    table.addItem(new Object[] {calendar.getTime(),
                                new Boolean(false),
                                ""},
                  new Integer(i)); // Item identifier
}

table.setPageLength(8);
layout.addComponent(table);

You could put the table in editable mode right away if you need to. We'll continue the example by adding a mechanism to switch the Table from and to the editable mode.

final CheckBox switchEditable = new CheckBox("Editable");
switchEditable.addValueChangeListener(
        new Property.ValueChangeListener() {
    public void valueChange(ValueChangeEvent event) {
        table.setEditable(((Boolean)event.getProperty()
                             .getValue()).booleanValue());
    }
});
switchEditable.setImmediate(true);
layout.addComponent(switchEditable);

Now, when you check to checkbox, the components in the table turn into editable fields, as shown in Figure 5.50, “A Table in Normal and Editable Mode”.

Figure 5.50. A Table in Normal and Editable Mode

A Table in Normal and Editable Mode

Field Factories

The field components that allow editing the values of particular types in a table are defined in a field factory that implements the TableFieldFactory interface. The default implementation is DefaultFieldFactory, which offers the following crude mappings:

Table 5.2. Type to Field Mappings in DefaultFieldFactory

Property TypeMapped to Field Class
DateA DateField.
BooleanA CheckBox.
ItemA Form (deprecated in Vaadin 7). The fields of the form are automatically created from the item's properties using a FormFieldFactory. The normal use for this property type is inside a Form and is less useful inside a Table.
otherA TextField. The text field manages conversions from the basic types, if possible.

Field factories are covered with more detail in Section 9.4, “Creating Forms by Binding Fields to Items”. You could just implement the TableFieldFactory interface, but we recommend that you extend the DefaultFieldFactory according to your needs. In the default implementation, the mappings are defined in the createFieldByPropertyType() method (you might want to look at the source code) both for tables and forms.

Navigation in Editable Mode

In the editable mode, the editor fields can have focus. Pressing Tab moves the focus to next column or, at the last column, to the first column of the next item. Respectively, pressing Shift+Tab moves the focus backward. If the focus is in the last column of the last visible item, the pressing Tab moves the focus outside the table. Moving backward from the first column of the first item moves the focus to the table itself. Some updates to the table, such as changing the headers or footers or regenerating a column, can move the focus from an editor component to the table itself.

The default behaviour may be undesirable in many cases. For example, the focus also goes through any read-only editor fields and can move out of the table inappropriately. You can provide better navigation is to use event handler for shortcut keys such as Tab, Arrow Up, Arrow Down, and Enter.

// Keyboard navigation
class KbdHandler implements Handler {
    Action tab_next = new ShortcutAction("Tab",
            ShortcutAction.KeyCode.TAB, null);
    Action tab_prev = new ShortcutAction("Shift+Tab",
            ShortcutAction.KeyCode.TAB,
            new int[] {ShortcutAction.ModifierKey.SHIFT});
    Action cur_down = new ShortcutAction("Down",
            ShortcutAction.KeyCode.ARROW_DOWN, null);
    Action cur_up   = new ShortcutAction("Up",
            ShortcutAction.KeyCode.ARROW_UP,   null);
    Action enter   = new ShortcutAction("Enter",
            ShortcutAction.KeyCode.ENTER,      null);
    public Action[] getActions(Object target, Object sender) {
        return new Action[] {tab_next, tab_prev, cur_down,
                             cur_up, enter};
    }

    public void handleAction(Action action, Object sender,
                             Object target) {
        if (target instanceof TextField) {
            // Move according to keypress
            int itemid = (Integer) ((TextField) target).getData();
            if (action == tab_next || action == cur_down)
                itemid++;
            else if (action == tab_prev || action == cur_up)
                itemid--;
            // On enter, just stay where you were. If we did
            // not catch the enter action, the focus would be
            // moved to wrong place.
            
            if (itemid >= 0 && itemid < table.size()) {
                TextField newTF = valueFields.get(itemid);
                if (newTF != null)
                    newTF.focus();
            }
        }
    }
}

// Panel that handles keyboard navigation
Panel navigator = new Panel();
navigator.addStyleName(Reindeer.PANEL_LIGHT);
navigator.addComponent(table);
navigator.addActionHandler(new KbdHandler());

The main issue in implementing keyboard navigation in an editable table is that the editor fields do not know the table they are in. To find the parent table, you can either look up in the component container hierarchy or simply store a reference to the table with setData() in the field component. The other issue is that you can not acquire a reference to an editor field from the Table component. One solution is to use some external collection, such as a HashMap, to map item IDs to the editor fields.

// Can't access the editable components from the table so
// must store the information
final HashMap<Integer,TextField> valueFields =
    new HashMap<Integer,TextField>();

The map has to be filled in a TableFieldFactory, such as in the following. You also need to set the reference to the table there and you can also set the initial focus there.

table.setTableFieldFactory(new TableFieldFactory () {
    public Field createField(Container container, Object itemId,
            Object propertyId, Component uiContext) {
        TextField field = new TextField((String) propertyId);
        
        // User can only edit the numeric column
        if ("Source of Fear".equals(propertyId))
            field.setReadOnly(true);
        else { // The numeric column
            // The field needs to know the item it is in
            field.setData(itemId);
            
            // Remember the field
            valueFields.put((Integer) itemId, field);
            
            // Focus the first editable value
            if (((Integer)itemId) == 0)
                field.focus();
        }
        return field;
    }
});

The issues are complicated by the fact that the editor fields are not generated for the entire table, but only for a cache window that includes the visible items and some items above and below it. For example, if the beginning of a big scrollable table is visible, the editor component for the last item does not exist. This issue is relevant mostly if you want to have wrap-around navigation that jumps from the last to first item and vice versa.

5.16.4. Column Headers and Footers

Table supports both column headers and footers; the headers are enabled by default.

Headers

The table header displays the column headers at the top of the table. You can use the column headers to reorder or resize the columns, as described earlier. By default, the header of a column is the property ID of the column, unless given explicitly with setColumnHeader().

// Define the properties
table.addContainerProperty("lastname", String.class, null);
table.addContainerProperty("born", Integer.class, null);
table.addContainerProperty("died", Integer.class, null);

// Set nicer header names
table.setColumnHeader("lastname", "Name");
table.setColumnHeader("born", "Born");
table.setColumnHeader("died", "Died");

The text of the column headers and the visibility of the header depends on the column header mode. The header is visible by default, but you can disable it with setColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN).

Footers

The table footer can be useful for displaying sums or averages of values in a column, and so on. The footer is not visible by default; you can enable it with setFooterVisible(true). Unlike in the header, the column headers are empty by default. You can set their value with setColumnFooter(). The columns are identified by their property ID.

The following example shows how to calculate average of the values in a column:

// Have a table with a numeric column
Table table = new Table("Custom Table Footer");
table.addContainerProperty("Name", String.class, null);
table.addContainerProperty("Died At Age", Integer.class, null);
        
// Insert some data
Object people[][] = {{"Galileo",  77},
                     {"Monnier",  83},
                     {"Vaisala",  79},
                     {"Oterma",   86}};
for (int i=0; i<people.length; i++)
    table.addItem(people[i], new Integer(i));
        
// Calculate the average of the numeric column
double avgAge = 0;
for (int i=0; i<people.length; i++)
    avgAge += (Integer) people[i][1];
avgAge /= people.length;

// Set the footers
table.setFooterVisible(true);
table.setColumnFooter("Name", "Average");
table.setColumnFooter("Died At Age", String.valueOf(avgAge));

// Adjust the table height a bit
table.setPageLength(table.size());

The resulting table is shown in Figure 5.51, “A Table with a Footer”.

Figure 5.51. A Table with a Footer

A Table with a Footer

Handling Mouse Clicks on Headers and Footers

Normally, when the user clicks a column header, the table will be sorted by the column, assuming that the data source is Sortable and sorting is not disabled. In some cases, you might want some other functionality when the user clicks the column header, such as selecting the column in some way.

Clicks in the header cause a HeaderClickEvent, which you can handle with a Table.HeaderClickListener. Click events on the table header (and footer) are, like button clicks, sent immediately to server, so there is no need to set setImmediate().

// Handle the header clicks
table.addHeaderClickListener(new Table.HeaderClickListener() {
    public void headerClick(HeaderClickEvent event) {
        String column = (String) event.getPropertyId();
        Notification.show("Clicked " + column +
                "with " + event.getButtonName());
    }
});
        
// Disable the default sorting behavior
table.setSortDisabled(true);

Setting a click handler does not automatically disable the sorting behavior of the header; you need to disable it explicitly with setSortDisabled(true). Header click events are not sent when the user clicks the column resize handlers to drag them.

The HeaderClickEvent object provides the identity of the clicked column with getPropertyId(). The getButton() reports the mouse button with which the click was made: BUTTON_LEFT, BUTTON_RIGHT, or BUTTON_MIDDLE. The getButtonName() a human-readable button name in English: "left", "right", or "middle". The isShiftKey(), isCtrlKey(), etc., methods indicate if the Shift, Ctrl, Alt or other modifier keys were pressed during the click.

Clicks in the footer cause a FooterClickEvent, which you can handle with a Table.FooterClickListener. Footers do not have any default click behavior, like the sorting in the header. Otherwise, handling clicks in the footer is equivalent to handling clicks in the header.

5.16.5. Generated Table Columns

You might want to have a column that has values calculated from other columns. Or you might want to format table columns in some way, for example if you have columns that display currencies. The ColumnGenerator interface allows defining custom generators for such columns.

You add new generated columns to a Table with addGeneratedColumn(). It takes the column identifier as its parameters. Usually you want to have a more user-friendly and possibly internationalized column header. You can set the header and a possible icon by calling addContainerProperty() before adding the generated column.

// Define table columns. 
table.addContainerProperty(
    "date",     Date.class,   null, "Date",         null, null);
table.addContainerProperty(
    "quantity", Double.class, null, "Quantity (l)", null, null);
table.addContainerProperty(
    "price",    Double.class, null, "Price (e/l)",  null, null);
table.addContainerProperty(
    "total",    Double.class, null, "Total (e)",    null, null);

// Define the generated columns and their generators.
table.addGeneratedColumn("date",
                         new DateColumnGenerator());
table.addGeneratedColumn("quantity",
                         new ValueColumnGenerator("%.2f l"));
table.addGeneratedColumn("price",
                         new PriceColumnGenerator());
table.addGeneratedColumn("total",
                         new ValueColumnGenerator("%.2f e"));

Notice that the addGeneratedColumn() always places the generated columns as the last column, even if you defined some other order previously. You will have to set the proper order with setVisibleColumns().

table.setVisibleColumns(new Object[] {"date", "quantity", "price", "total"});

The generators are objects that implement the Table.ColumnGenerator interface and its generateCell() method. The method gets the identity of the item and column as its parameters, in addition to the table object. It has to return a component object.

The following example defines a generator for formatting Double valued fields according to a format string (as in java.util.Formatter).

/** Formats the value in a column containing Double objects. */
class ValueColumnGenerator implements Table.ColumnGenerator {
    String format; /* Format string for the Double values. */

    /**
     * Creates double value column formatter with the given
     * format string.
     */
    public ValueColumnGenerator(String format) {
        this.format = format;
    }

    /**
     * Generates the cell containing the Double value.
     * The column is irrelevant in this use case.
     */
    public Component generateCell(Table source, Object itemId,
                                  Object columnId) {
        // Get the object stored in the cell as a property
        Property prop =
            source.getItem(itemId).getItemProperty(columnId);
        if (prop.getType().equals(Double.class)) {
            Label label = new Label(String.format(format,
                    new Object[] { (Double) prop.getValue() }));
            
            // Set styles for the column: one indicating that it's
            // a value and a more specific one with the column
            // name in it. This assumes that the column name
            // is proper for CSS.
            label.addStyleName("column-type-value");
            label.addStyleName("column-" + (String) columnId);
            return label;
        }
        return null;
    }
}

The generator is called for all the visible (or more accurately cached) items in a table. If the user scrolls the table to another position in the table, the columns of the new visible rows are generated dynamically. The columns in the visible (cached) rows are also generated always when an item has a value change. It is therefore usually safe to calculate the value of generated cells from the values of different rows (items).

When you set a table as editable, regular fields will change to editing fields. When the user changes the values in the fields, the generated columns will be updated automatically. Putting a table with generated columns in editable mode has a few quirks. The editable mode of Table does not affect generated columns. You have two alternatives: either you generate the editing fields in the generator or, in case of formatter generators, remove the generator in the editable mode. The example below uses the latter approach.

// Have a check box that allows the user
// to make the quantity and total columns editable.
final CheckBox editable = new CheckBox(
    "Edit the input values - calculated columns are regenerated");

editable.setImmediate(true);
editable.addClickListener(new ClickListener() {
    public void buttonClick(ClickEvent event) {
        table.setEditable(editable.booleanValue());
        
        // The columns may not be generated when we want to
        // have them editable.
        if (editable.booleanValue()) {
            table.removeGeneratedColumn("quantity");
            table.removeGeneratedColumn("total");
        } else { // Not editable
            // Show the formatted values.
            table.addGeneratedColumn("quantity",
                new ValueColumnGenerator("%.2f l"));
            table.addGeneratedColumn("total",
                new ValueColumnGenerator("%.2f e"));
        }
        // The visible columns are affected by removal
        // and addition of generated columns so we have
        // to redefine them.
        table.setVisibleColumns(new Object[] {"date", "quantity",
                 "price", "total", "consumption", "dailycost"});
    }
});

You will also have to set the editing fields in immediate mode to have the update occur immediately when an edit field loses the focus. You can set the fields in immediate mode with the a custom TableFieldFactory, such as the one given below, that just extends the default implementation to set the mode:

public class ImmediateFieldFactory extends DefaultFieldFactory {
    public Field createField(Container container,
                             Object itemId,
                             Object propertyId,
                             Component uiContext) {
        // Let the DefaultFieldFactory create the fields...
        Field field = super.createField(container, itemId,
                                        propertyId, uiContext);
        
        // ...and just set them as immediate.
        ((AbstractField)field).setImmediate(true);
        
        return field;
    }
}
...
table.setTableFieldFactory(new ImmediateFieldFactory());

If you generate the editing fields with the column generator, you avoid having to use such a field factory, but of course have to generate the fields for both normal and editable modes.

Figure 5.52, “Table with Generated Columns in Normal and Editable Mode” shows a table with columns calculated (blue) and simply formatted (black) with column generators.

Figure 5.52. Table with Generated Columns in Normal and Editable Mode

Table with Generated Columns in Normal and Editable Mode
Table with Generated Columns in Normal and Editable Mode

5.16.6. Formatting Table Columns

The displayed values of properties shown in a table are normally formatted using the toString() method of each property. Customizing the format of a column can be done in several ways:

  • Using ColumnGenerator to generate a second column that is formatted. The original column needs to be set invisible. See Section 5.16.5, “Generated Table Columns”.
  • Using a PropertyFormatter as a proxy between the table and the data property. This also normally requires using an mediate container in the table.
  • Overriding the default formatPropertyValue() in Table.

As using a PropertyFormatter is generally much more awkward than overriding the formatPropertyValue(), its use is not described here.

You can override formatPropertyValue() as is done in the following example:

// Create a table that overrides the default
// property (column) format
final Table table = new Table("Formatted Table") {
    @Override
    protected String formatPropertyValue(Object rowId,
            Object colId, Property property) {
        // Format by property type
        if (property.getType() == Date.class) {
            SimpleDateFormat df =
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            return df.format((Date)property.getValue());
        }

        return super.formatPropertyValue(rowId, colId, property);
    }
};
        
// The table has some columns
table.addContainerProperty("Time", Date.class, null);
        
... Fill the table with data ...

You can also distinguish between columns by the colId parameter, which is the property ID of the column. DecimalFormat is useful for formatting decimal values.

... in formatPropertyValue() ...
} else if ("Value".equals(pid)) {
    // Format a decimal value for a specific locale
    DecimalFormat df = new DecimalFormat("#.00",
            new DecimalFormatSymbols(locale));
    return df.format((Double) property.getValue());
}
...
table.addContainerProperty("Value", Double.class, null);

A table with the formatted date and decimal value columns is shown in Figure 5.53, “Formatted Table Columns”.

Figure 5.53. Formatted Table Columns

Formatted Table Columns

You can use CSS for further styling of table rows, columns, and individual cells by using a CellStyleGenerator. It is described in Section 5.16.7, “CSS Style Rules”.

5.16.7. CSS Style Rules

Styling the overall style of a Table can be done with the following CSS rules.

.v-table {}
  .v-table-header-wrap {}
    .v-table-header {}
      .v-table-header-cell {}
        .v-table-resizer {} /* Column resizer handle. */
        .v-table-caption-container {}
  .v-table-body {}
    .v-table-row-spacer {}
    .v-table-table {}
      .v-table-row {}
        .v-table-cell-content {}

Notice that some of the widths and heights in a table are calculated dynamically and can not be set in CSS.

Setting Individual Cell Styles

The Table.CellStyleGenerator interface allows you to set the CSS style for each individual cell in a table. You need to implement the getStyle(), which gets the row (item) and column (property) identifiers as parameters and can return a style name for the cell. The returned style name will be concatenated to prefix "v-table-cell-content-".

The getStyle() is called also for each row, so that the propertyId parameter is null. This allows setting a row style.

Alternatively, you can use a Table.ColumnGenerator (see Section 5.16.5, “Generated Table Columns”) to generate the actual UI components of the cells and add style names to them.

Table table = new Table("Table with Cell Styles");
table.addStyleName("checkerboard");

// Add some columns in the table. In this example, the property
// IDs of the container are integers so we can determine the
// column number easily.
table.addContainerProperty("0", String.class, null, "", null, null);
for (int i=0; i<8; i++)
    table.addContainerProperty(""+(i+1), String.class, null,
                         String.valueOf((char) (65+i)), null, null);

// Add some items in the table.
table.addItem(new Object[]{
    "1", "R", "N", "B", "Q", "K", "B", "N", "R"}, new Integer(0));
table.addItem(new Object[]{
    "2", "P", "P", "P", "P", "P", "P", "P", "P"}, new Integer(1));
for (int i=2; i<6; i++)
    table.addItem(new Object[]{String.valueOf(i+1), 
                 "", "", "", "", "", "", "", ""}, new Integer(i));
table.addItem(new Object[]{
    "7", "P", "P", "P", "P", "P", "P", "P", "P"}, new Integer(6));
table.addItem(new Object[]{
    "8", "R", "N", "B", "Q", "K", "B", "N", "R"}, new Integer(7));
table.setPageLength(8);

// Set cell style generator
table.setCellStyleGenerator(new Table.CellStyleGenerator() {
    public String getStyle(Object itemId, Object propertyId) {
        // Row style setting, not relevant in this example.
        if (propertyId == null)
            return "green"; // Will not actually be visible

        int row = ((Integer)itemId).intValue();
        int col = Integer.parseInt((String)propertyId);
        
        // The first column.
        if (col == 0)
            return "rowheader";
        
        // Other cells.
        if ((row+col)%2 == 0)
            return "black";
        else
            return "white";
    }
});

You can then style the cells, for example, as follows:

/* Center the text in header. */
.v-table-header-cell {
    text-align: center;
}

/* Basic style for all cells. */
.v-table-checkerboard .v-table-cell-content {
    text-align: center;
    vertical-align: middle;
    padding-top: 12px;
    width: 20px;
    height: 28px;
}

/* Style specifically for the row header cells. */
.v-table-cell-content-rowheader {
	background: #E7EDF3
     url(../default/table/img/header-bg.png) repeat-x scroll 0 0;
}

/* Style specifically for the "white" cells. */
.v-table-cell-content-white {
    background: white;
    color: black;
}

/* Style specifically for the "black" cells. */
.v-table-cell-content-black {
    background: black;
    color: white;
}

The table will look as shown in Figure 5.54, “Cell Style Generator for a Table”.

Figure 5.54. Cell Style Generator for a Table

Cell Style Generator for a Table

Preface
I. Introduction
1. Introduction
1.1. Overview
1.2. Example Application Walkthrough
1.3. Support for the Eclipse IDE
1.4. Goals and Philosophy
1.5. Background
2. Getting Started with Vaadin
2.1. Overview
2.2. Setting up the Development Environment
2.3. Overview of Vaadin Libraries
2.4. Installing Vaadin Plugin for Eclipse
2.5. Creating and Running a Project with Eclipse
2.6. Using Vaadin with Maven
2.7. Creating a Project with NetBeans IDE
2.8. Creating a Project with IntelliJ IDEA
2.9. Vaadin Installation Package
2.10. Using Vaadin with Scala
3. Architecture
3.1. Overview
3.2. Technological Background
3.3. Client-Side Engine
3.4. Events and Listeners
II. Server-Side Framework
4. Writing a Server-Side Web Application
4.1. Overview
4.2. Building the UI
4.3. Handling Events with Listeners
4.4. Images and Other Resources
4.5. Handling Errors
4.6. Notifications
4.7. Application Lifecycle
4.8. Deploying an Application
5. User Interface Components
5.1. Overview
5.2. Interfaces and Abstractions
5.3. Common Component Features
5.4. Field Components
5.5. Component Extensions
5.6. Label
5.7. Link
5.8. TextField
5.9. TextArea
5.10. PasswordField
5.11. RichTextArea
5.12. Date and Time Input with DateField
5.13. Button
5.14. CheckBox
5.15. Selecting Items
5.16. Table
5.17. Tree
5.18. MenuBar
5.19. Embedded Resources
5.20. Upload
5.21. ProgressBar
5.22. Slider
5.23. Calendar
5.24. Component Composition with CustomComponent
5.25. Composite Fields with CustomField
6. Managing Layout
6.1. Overview
6.2. UI, Window, and Panel Content
6.3. VerticalLayout and HorizontalLayout
6.4. GridLayout
6.5. FormLayout
6.6. Panel
6.7. Sub-Windows
6.8. HorizontalSplitPanel and VerticalSplitPanel
6.9. TabSheet
6.10. Accordion
6.11. AbsoluteLayout
6.12. CssLayout
6.13. Layout Formatting
6.14. Custom Layouts
7. Visual User Interface Design with Eclipse
7.1. Overview
7.2. Creating a New Composite
7.3. Using The Visual Editor
7.4. Structure of a Visually Editable Component
8. Themes
8.1. Overview
8.2. Introduction to Cascading Style Sheets
8.3. Syntactically Awesome Stylesheets (Sass)
8.4. Creating and Using Themes
8.5. Creating a Theme in Eclipse
8.6. Responsive Themes
9. Binding Components to Data
9.1. Overview
9.2. Properties
9.3. Holding properties in Items
9.4. Creating Forms by Binding Fields to Items
9.5. Collecting Items in Containers
10. Vaadin SQLContainer
10.1. Architecture
10.2. Getting Started with SQLContainer
10.3. Filtering and Sorting
10.4. Editing
10.5. Caching, Paging and Refreshing
10.6. Referencing Another SQLContainer
10.7. Using FreeformQuery and FreeformStatementDelegate
10.8. Non-implemented methods of Vaadin container interfaces
10.9. Known Issues and Limitations
11. Advanced Web Application Topics
11.1. Handling Browser Windows
11.2. Embedding UIs in Web Pages
11.3. Debug Mode and Window
11.4. Request Handlers
11.5. Shortcut Keys
11.6. Printing
11.7. Google App Engine Integration
11.8. Common Security Issues
11.9. Navigating in an Application
11.10. Advanced Application Architectures
11.11. Managing URI Fragments
11.12. Drag and Drop
11.13. Logging
11.14. JavaScript Interaction
11.15. Accessing Session-Global Data
11.16. Server Push
12. Portal Integration
12.1. Overview
12.2. Creating a Portlet Project in Eclipse
12.3. Portlet UI
12.4. Deploying to a Portal
12.5. Installing Vaadin in Liferay
12.6. Handling Portlet Requests
12.7. Handling Portlet Mode Changes
12.8. Non-Vaadin Portlet Modes
12.9. Vaadin IPC for Liferay
III. Client-Side Framework
13. Client-Side Vaadin Development
13.1. Overview
13.2. Installing the Client-Side Development Environment
13.3. Client-Side Module Descriptor
13.4. Compiling a Client-Side Module
13.5. Creating a Custom Widget
13.6. Debugging Client-Side Code
14. Client-Side Applications
14.1. Overview
14.2. Client-Side Module Entry-Point
14.3. Compiling and Running a Client-Side Application
14.4. Loading a Client-Side Application
15. Client-Side Widgets
15.1. Overview
15.2. GWT Widgets
15.3. Vaadin Widgets
16. Integrating with the Server-Side
16.1. Overview
16.2. Starting It Simple With Eclipse
16.3. Creating a Server-Side Component
16.4. Integrating the Two Sides with a Connector
16.5. Shared State
16.6. RPC Calls Between Client- and Server-Side
16.7. Component and UI Extensions
16.8. Styling a Widget
16.9. Component Containers
16.10. Creating Add-ons
16.11. Migrating from Vaadin 6
16.12. Integrating JavaScript Components and Extensions
IV. Vaadin Add-ons
17. Using Vaadin Add-ons
17.1. Overview
17.2. Downloading Add-ons from Vaadin Directory
17.3. Installing Add-ons in Eclipse with Ivy
17.4. Using Add-ons in a Maven Project
17.5. Troubleshooting
18. Vaadin Charts
18.1. Overview
18.2. Installing Vaadin Charts
18.3. Basic Use
18.4. Chart Types
18.5. Chart Configuration
18.6. Chart Data
18.7. Advanced Uses
18.8. Timeline
19. Vaadin JPAContainer
19.1. Overview
19.2. Installing
19.3. Defining a Domain Model
19.4. Basic Use of JPAContainer
19.5. Entity Providers
19.6. Filtering JPAContainer
19.7. Querying with the Criteria API
19.8. Automatic Form Generation
19.9. Using JPAContainer with Hibernate
20. Mobile Applications with TouchKit
20.1. Overview
20.2. Considerations Regarding Mobile Browsing
20.3. Installing Vaadin TouchKit
20.4. Importing the Vornitologist Demo
20.5. Creating a New TouchKit Project
20.6. Elements of a TouchKit Application
20.7. Mobile User Interface Components
20.8. Advanced Mobile Features
20.9. Offline Mode
20.10. Building an Optimized Widget Set
20.11. Testing and Debugging on Mobile Devices
21. Vaadin TestBench
21.1. Overview
21.2. Installing Vaadin TestBench
21.3. Preparing an Application for Testing
21.4. Using Vaadin TestBench Recorder
21.5. Developing JUnit Tests
21.6. Taking and Comparing Screenshots
21.7. Running Tests in a Distributed Environment
21.8. Headless Testing
21.9. Known Issues
A. Songs of Vaadin
Index