Table

Live Demo

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 Vaadin data model (see “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.)

Java

  1. Table table = new Table("The Brightest Stars");
  2. // Define two columns for the built-in container
  3. table.addContainerProperty("Name", String.class, null);
  4. table.addContainerProperty("Mag", Float.class, null);
  5. // Add a row the hard way
  6. Object newItemId = table.addItem();
  7. Item row1 = table.getItem(newItemId);
  8. row1.getItemProperty("Name").setValue("Sirius");
  9. row1.getItemProperty("Mag").setValue(-1.46f);
  10. // Add a few other rows using shorthand addItem()
  11. table.addItem(new Object[]{"Canopus", -0.72f}, 2);
  12. table.addItem(new Object[]{"Arcturus", -0.04f}, 3);
  13. table.addItem(new Object[]{"Alpha Centauri", -0.01f}, 4);
  14. // Show exactly the currently contained rows (items)
  15. table.setPageLength(table.size());

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.

table example1

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.

Common selection component features are described in “Selection Components”.

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.

Java

  1. // Allow selecting items from the table.
  2. table.setSelectable(true);
  3. // Send changes in selection immediately to server.
  4. table.setImmediate(true);
  5. // Shows feedback from selection.
  6. final Label current = new Label("Selected: -");
  7. // Handle selection change.
  8. table.addValueChangeListener(new Property.ValueChangeListener() {
  9. public void valueChange(ValueChangeEvent event) {
  10. current.setValue("Selected: " + table.getValue());
  11. }
  12. });

table example2

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.

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.

Java

  1. table.addColumnResizeListener(new Table.ColumnResizeListener(){
  2. public void columnResize(ColumnResizeEvent event) {
  3. // Get the new width of the resized column
  4. int width = event.getCurrentWidth();
  5. // Get the property ID of the resized column
  6. String column = (String) event.getPropertyId();
  7. // Do something with the information
  8. table.setColumnFooter(column, String.valueOf(width) + "px");
  9. }
  10. });
  11. // Must be immediate to send the resize events immediately
  12. table.setImmediate(true);

See Resizing Columns for a result after the columns of a table has been resized.

table column resize

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.

Java

  1. // Allow the user to collapse and uncollapse columns
  2. table.setColumnCollapsingAllowed(true);
  3. // Collapse this column programmatically
  4. try {
  5. table.setColumnCollapsed("born", true);
  6. } catch (IllegalAccessException e) {
  7. // Can't occur - collapsing was allowed above
  8. System.err.println("Something horrible occurred");
  9. }
  10. // Give enough width for the table to accommodate the
  11. // initially collapsed column later
  12. table.setWidth("250px");

See Collapsing Columns.

table column collapsing

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 HTML content mode, a multiline TextField, a CheckBox, and a Button that shows as a link.

Java

  1. // Create a table and add a style to
  2. // allow setting the row height in theme.
  3. Table table = new Table();
  4. table.addStyleName("components-inside");
  5. /* Define the names and data types of columns.
  6. * The "default value" parameter is meaningless here. */
  7. table.addContainerProperty("Sum", Label.class, null);
  8. table.addContainerProperty("Is Transferred", CheckBox.class, null);
  9. table.addContainerProperty("Comments", TextField.class, null);
  10. table.addContainerProperty("Details", Button.class, null);
  11. /* Add a few items in the table. */
  12. for (int i=0; i<100; i++) {
  13. // Create the fields for the current table row
  14. Label sumField = new Label(String.format(
  15. "Sum is <b>$%04.2f</b><br/><i>(VAT incl.)</i>",
  16. new Object[] {new Double(Math.random()*1000)}),
  17. ContentMode.HTML);
  18. CheckBox transferredField = new CheckBox("is transferred");
  19. // Multiline text field. This required modifying the
  20. // height of the table row.
  21. TextField commentsField = new TextField();
  22. commentsField.setRows(3);
  23. // The Table item identifier for the row.
  24. Integer itemId = new Integer(i);
  25. // Create a button and handle its click. A Button does not
  26. // know the item it is contained in, so we have to store the
  27. // item ID as user-defined data.
  28. Button detailsField = new Button("show details");
  29. detailsField.setData(itemId);
  30. detailsField.addClickListener(new Button.ClickListener() {
  31. public void buttonClick(ClickEvent event) {
  32. // Get the item identifier from the user-defined data.
  33. Integer iid = (Integer)event.getButton().getData();
  34. Notification.show("Link " +
  35. iid.intValue() + " clicked.");
  36. }
  37. });
  38. detailsField.addStyleName("link");
  39. // Create the table row.
  40. table.addItem(new Object[] {sumField, transferredField,
  41. commentsField, detailsField},
  42. itemId);
  43. }
  44. // Show just three rows because they are so high.
  45. table.setPageLength(3);

See the on-line example.

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

CSS

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

See the on-line example.

The table will look as shown in Components in a Table.

table components

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 “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 “Filterable Containers”.

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 earlier or simply call setEditable(true), in which case 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.

Java

  1. // Create a table. It is by default not editable.
  2. Table table = new Table();
  3. // Define the names and data types of columns.
  4. table.addContainerProperty("Date", Date.class, null);
  5. table.addContainerProperty("Work", Boolean.class, null);
  6. table.addContainerProperty("Comments", String.class, null);
  7. ...

You could put the table in editable mode right away. We continue the example by adding a check box to switch the table between normal and editable modes:

Java

  1. CheckBox editable = new CheckBox("Editable", true);
  2. editable.addValueChangeListener(valueChange -> // Java 8
  3. table.setEditable((Boolean) editable.getValue()));

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

table editable3

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 1. Type to Field Mappings in DefaultFieldFactory
Property TypeMapped to Field Class

Date

A DateField.

Boolean

A CheckBox.

Item

A 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.

other

A TextField. The text field manages conversions from the basic types, if possible.

Field factories are covered with more detail in “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.

Java

  1. // Keyboard navigation
  2. class KbdHandler implements Handler {
  3. Action tab_next = new ShortcutAction("Tab",
  4. ShortcutAction.KeyCode.TAB, null);
  5. Action tab_prev = new ShortcutAction("Shift+Tab",
  6. ShortcutAction.KeyCode.TAB,
  7. new int[] {ShortcutAction.ModifierKey.SHIFT});
  8. Action cur_down = new ShortcutAction("Down",
  9. ShortcutAction.KeyCode.ARROW_DOWN, null);
  10. Action cur_up = new ShortcutAction("Up",
  11. ShortcutAction.KeyCode.ARROW_UP, null);
  12. Action enter = new ShortcutAction("Enter",
  13. ShortcutAction.KeyCode.ENTER, null);
  14. public Action[] getActions(Object target, Object sender) {
  15. return new Action[] {tab_next, tab_prev, cur_down,
  16. cur_up, enter};
  17. }
  18. public void handleAction(Action action, Object sender,
  19. Object target) {
  20. if (target instanceof TextField) {
  21. // Move according to keypress
  22. int itemid = (Integer) ((TextField) target).getData();
  23. if (action == tab_next || action == cur_down)
  24. itemid++;
  25. else if (action == tab_prev || action == cur_up)
  26. itemid--;
  27. // On enter, just stay where you were. If we did
  28. // not catch the enter action, the focus would be
  29. // moved to wrong place.
  30. if (itemid >= 0 && itemid < table.size()) {
  31. TextField newTF = valueFields.get(itemid);
  32. if (newTF != null)
  33. newTF.focus();
  34. }
  35. }
  36. }
  37. }
  38. // Panel that handles keyboard navigation
  39. Panel navigator = new Panel();
  40. navigator.addStyleName(Reindeer.PANEL_LIGHT);
  41. navigator.addComponent(table);
  42. 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.

Java

  1. // Can't access the editable components from the table so
  2. // must store the information
  3. final HashMap<Integer,TextField> valueFields =
  4. 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.

Java

  1. table.setTableFieldFactory(new TableFieldFactory () {
  2. public Field createField(Container container, Object itemId,
  3. Object propertyId, Component uiContext) {
  4. TextField field = new TextField((String) propertyId);
  5. // User can only edit the numeric column
  6. if ("Source of Fear".equals(propertyId))
  7. field.setReadOnly(true);
  8. else { // The numeric column
  9. // The field needs to know the item it is in
  10. field.setData(itemId);
  11. // Remember the field
  12. valueFields.put((Integer) itemId, field);
  13. // Focus the first editable value
  14. if (((Integer)itemId) == 0)
  15. field.focus();
  16. }
  17. return field;
  18. }
  19. });

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.

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().

Java

  1. // Define the properties
  2. table.addContainerProperty("lastname", String.class, null);
  3. table.addContainerProperty("born", Integer.class, null);
  4. table.addContainerProperty("died", Integer.class, null);
  5. // Set nicer header names
  6. table.setColumnHeader("lastname", "Name");
  7. table.setColumnHeader("born", "Born");
  8. 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:

Java

  1. // Have a table with a numeric column
  2. Table table = new Table("Custom Table Footer");
  3. table.addContainerProperty("Name", String.class, null);
  4. table.addContainerProperty("Died At Age", Integer.class, null);
  5. // Insert some data
  6. Object people[][] = { {"Galileo", 77},
  7. {"Monnier", 83},
  8. {"Vaisala", 79},
  9. {"Oterma", 86}};
  10. for (int i=0; i<people.length; i++)
  11. table.addItem(people[i], new Integer(i));
  12. // Calculate the average of the numeric column
  13. double avgAge = 0;
  14. for (int i=0; i<people.length; i++)
  15. avgAge += (Integer) people[i][1];
  16. avgAge /= people.length;
  17. // Set the footers
  18. table.setFooterVisible(true);
  19. table.setColumnFooter("Name", "Average");
  20. table.setColumnFooter("Died At Age", String.valueOf(avgAge));
  21. // Adjust the table height a bit
  22. table.setPageLength(table.size());

The resulting table is shown in A Table with a Footer.

table 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().

Java

  1. // Handle the header clicks
  2. table.addHeaderClickListener(new Table.HeaderClickListener() {
  3. public void headerClick(HeaderClickEvent event) {
  4. String column = (String) event.getPropertyId();
  5. Notification.show("Clicked " + column +
  6. "with " + event.getButtonName());
  7. }
  8. });
  9. // Disable the default sorting behavior
  10. 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.

Generated Table Columns

A table can have generated columns which values can be calculated based on the values in other columns. The columns are generated with a class implementing the Table.ColumnGenerator interface.

The GeneratedPropertyContainer described in “GeneratedPropertyContainer” is another way to accomplish the same task at container level. In addition to generating values, you can also use the feature for formatting or styling columns.

Defining a Column Generator

Column 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, and has to return a component. The interface is functional, so you can also define it by a lambda expression or a method reference in Java 8.

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

Java

  1. /** Formats the value in a column containing Double objects. */
  2. class ValueColumnGenerator implements Table.ColumnGenerator {
  3. String format; /* Format string for the Double values. */
  4. /**
  5. * Creates double value column formatter with the given
  6. * format string.
  7. */
  8. public ValueColumnGenerator(String format) {
  9. this.format = format;
  10. }
  11. /**
  12. * Generates the cell containing the Double value.
  13. * The column is irrelevant in this use case.
  14. */
  15. public Component generateCell(Table source, Object itemId,
  16. Object columnId) {
  17. // Get the object stored in the cell as a property
  18. Property prop =
  19. source.getItem(itemId).getItemProperty(columnId);
  20. if (prop.getType().equals(Double.class)) {
  21. Label label = new Label(String.format(format,
  22. new Object[] { (Double) prop.getValue() }));
  23. // Set styles for the column: one indicating that it's
  24. // a value and a more specific one with the column
  25. // name in it. This assumes that the column name
  26. // is proper for CSS.
  27. label.addStyleName("column-type-value");
  28. label.addStyleName("column-" + (String) columnId);
  29. return label;
  30. }
  31. return null;
  32. }
  33. }

The column 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.

Generated column cells are automatically updated when a property value in the table row changes. Note that a generated cell, even if it is a field, does not normally have a property value bound to the table’s container, so changes in generated columns do not trigger updates in other generated columns. It should also be noted that if a generated column cell depends on values in other rows, changes in the other rows do not trigger automatic update. You can get notified of such value changes by listening for them with a ValueChangeListener in the generated components. If you do so, you must remove such listeners when the generated components are detached from the UI or otherwise the listeners will accumulate in the container when the table is scrolled back and forth, causing possibly severe memory leak.

Adding Generated Columns

You add new generated columns to a Table with addGeneratedColumn(). It takes a property ID of the generated column as the first parameter and the generator as the second.

Java

  1. // Define the generated columns and their generators
  2. table.addGeneratedColumn("date", // Java 8:
  3. this::generateNonEditableCell);
  4. table.addGeneratedColumn("price",
  5. new PriceColumnGenerator());
  6. table.addGeneratedColumn("consumption",
  7. new ConsumptionColumnGenerator());
  8. table.addGeneratedColumn("dailycost",
  9. new DailyCostColumnGenerator());

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().

Java

  1. table.setVisibleColumns("date", "quantity", "price", "total");

Generators in Editable Table

When you set a table as editable, table cells change to editable fields. When the user changes the values in the fields, the generated cells in the same row are updated automatically. However, putting a table with generated columns in editable mode has a few quirks. One is that the editable mode 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 generators in the editable mode to allow editing the values. The following example uses the latter approach.

Java

  1. // Have a check box that allows the user
  2. // to make the quantity and total columns editable.
  3. final CheckBox editable = new CheckBox(
  4. "Edit the input values - calculated columns are regenerated");
  5. editable.setImmediate(true);
  6. editable.addClickListener(new ClickListener() {
  7. public void buttonClick(ClickEvent event) {
  8. table.setEditable(editable.booleanValue());
  9. // The columns may not be generated when we want to
  10. // have them editable.
  11. if (editable.booleanValue()) {
  12. table.removeGeneratedColumn("quantity");
  13. table.removeGeneratedColumn("total");
  14. } else { // Not editable
  15. // Show the formatted values.
  16. table.addGeneratedColumn("quantity",
  17. new ValueColumnGenerator("%.2f l"));
  18. table.addGeneratedColumn("total",
  19. new ValueColumnGenerator("%.2f e"));
  20. }
  21. // The visible columns are affected by removal
  22. // and addition of generated columns so we have
  23. // to redefine them.
  24. table.setVisibleColumns("date", "quantity",
  25. "price", "total", "consumption", "dailycost");
  26. }
  27. });

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:

Java

  1. public class ImmediateFieldFactory extends DefaultFieldFactory {
  2. public Field createField(Container container,
  3. Object itemId,
  4. Object propertyId,
  5. Component uiContext) {
  6. // Let the DefaultFieldFactory create the fields...
  7. Field field = super.createField(container, itemId,
  8. propertyId, uiContext);
  9. // ...and just set them as immediate.
  10. ((AbstractField)field).setImmediate(true);
  11. return field;
  12. }
  13. }
  14. ...
  15. 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.

Table with generated columns shows a table with columns calculated (blue) and simply formatted (black) with column generators.

table generatedcolumns1

Table with generated columns

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 in a table 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 Generated Table Columns.

  • Using a Converter to convert between the property data model and its representation in the table.

  • Using a GeneratedPropertyContainer as a wrapper around the actual container to provide formatting.

  • 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:

Java

  1. // Create a table that overrides the default
  2. // property (column) format
  3. final Table table = new Table("Formatted Table") {
  4. @Override
  5. protected String formatPropertyValue(Object rowId,
  6. Object colId, Property property) {
  7. // Format by property type
  8. if (property.getType() == Date.class) {
  9. SimpleDateFormat df =
  10. new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  11. return df.format((Date)property.getValue());
  12. }
  13. return super.formatPropertyValue(rowId, colId, property);
  14. }
  15. };
  16. // The table has some columns
  17. table.addContainerProperty("Time", Date.class, null);
  18. ... 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.

Java

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

A table with the formatted date and decimal value columns is shown in Formatted Table columns.

table columnformatting

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 CSS Style Rules.

CSS Style Rules

CSS

  1. .v-table {}
  2. .v-table-header-wrap {}
  3. .v-table-header {}
  4. .v-table-header-cell {}
  5. .v-table-resizer {} /* Column resizer handle. */
  6. .v-table-caption-container {}
  7. .v-table-body {}
  8. .v-table-row-spacer {}
  9. .v-table-table {}
  10. .v-table-row {}
  11. .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.

Generating Cell Styles With CellStyleGenerator

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 Generated Table Columns) to generate the actual UI components of the cells and add style names to them.

Java

  1. Table table = new Table("Table with Cell Styles");
  2. table.addStyleName("checkerboard");
  3. // Add some columns in the table. In this example, the property
  4. // IDs of the container are integers so we can determine the
  5. // column number easily.
  6. table.addContainerProperty("0", String.class, null, "", null, null);
  7. for (int i=0; i<8; i++)
  8. table.addContainerProperty(""+(i+1), String.class, null,
  9. String.valueOf((char) (65+i)), null, null);
  10. // Add some items in the table.
  11. table.addItem(new Object[]{
  12. "1", "R", "N", "B", "Q", "K", "B", "N", "R"}, new Integer(0));
  13. table.addItem(new Object[]{
  14. "2", "P", "P", "P", "P", "P", "P", "P", "P"}, new Integer(1));
  15. for (int i=2; i<6; i++)
  16. table.addItem(new Object[]{String.valueOf(i+1),
  17. "", "", "", "", "", "", "", ""}, new Integer(i));
  18. table.addItem(new Object[]{
  19. "7", "P", "P", "P", "P", "P", "P", "P", "P"}, new Integer(6));
  20. table.addItem(new Object[]{
  21. "8", "R", "N", "B", "Q", "K", "B", "N", "R"}, new Integer(7));
  22. table.setPageLength(8);
  23. // Set cell style generator
  24. table.setCellStyleGenerator(new Table.CellStyleGenerator() {
  25. public String getStyle(Object itemId, Object propertyId) {
  26. // Row style setting, not relevant in this example.
  27. if (propertyId == null)
  28. return "green"; // Will not actually be visible
  29. int row = ((Integer)itemId).intValue();
  30. int col = Integer.parseInt((String)propertyId);
  31. // The first column.
  32. if (col == 0)
  33. return "rowheader";
  34. // Other cells.
  35. if ((row+col)%2 == 0)
  36. return "black";
  37. else
  38. return "white";
  39. }
  40. });

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

CSS

  1. /* Center the text in header. */
  2. .v-table-header-cell {
  3. text-align: center;
  4. }
  5. /* Basic style for all cells. */
  6. .v-table-checkerboard .v-table-cell-content {
  7. text-align: center;
  8. vertical-align: middle;
  9. padding-top: 12px;
  10. width: 20px;
  11. height: 28px;
  12. }
  13. /* Style specifically for the row header cells. */
  14. .v-table-cell-content-rowheader {
  15. background: #E7EDF3
  16. url(../default/table/img/header-bg.png) repeat-x scroll 0 0;
  17. }
  18. /* Style specifically for the "white" cells. */
  19. .v-table-cell-content-white {
  20. background: white;
  21. color: black;
  22. }
  23. /* Style specifically for the "black" cells. */
  24. .v-table-cell-content-black {
  25. background: black;
  26. color: white;
  27. }

The table will look as shown in Cell style generator for a Table.

table cellstylegenerator1

Cell style generator for a Table