Collecting Items in Containers

The Container interface is the highest containment level of the Vaadin data model, for containing items (rows) which in turn contain properties (columns). Containers can therefore represent tabular data, which can be viewed in a Table or some other selection component, as well as hierarchical data.

The items contained in a container are identified by an item identifier or IID, and the properties by a property identifier or PID.

Basic Use of Containers

The basic use of containers involves creating one, adding items to it, and binding it as a container data source of a component.

Default Containers and Delegation

Before saying anything about creation of containers, it should be noted that all components that can be bound to a container data source are by default bound to a default container. For example, Table is bound to a IndexedContainer, Tree to a HierarchicalContainer, and so forth.

All of the user interface components using containers also implement the relevant container interfaces themselves, so that the access to the underlying data source is delegated through the component.

  1. // Create a table with one column
  2. Table table = new Table("My Table");
  3. table.addContainerProperty("col1", String.class, null);
  4. // Access items and properties through the component
  5. table.addItem("row1"); // Create item by explicit ID
  6. Item item1 = table.getItem("row1");
  7. Property property1 = item1.getItemProperty("col1");
  8. property1.setValue("some given value");
  9. // Equivalent access through the container
  10. Container container = table.getContainerDataSource();
  11. container.addItem("row2");
  12. Item item2 = container.getItem("row2");
  13. Property property2 = item2.getItemProperty("col1");
  14. property2.setValue("another given value");

Creating and Binding a Container

A container is created and bound to a component as follows:

  1. // Create a container of some type
  2. Container container = new IndexedContainer();
  3. // Initialize the container as required by the container type
  4. container.addContainerProperty("name", String.class, "none");
  5. container.addContainerProperty("volume", Double.class, 0.0);
  6. ... add items ...
  7. // Bind it to a component
  8. Table table = new Table("My Table");
  9. table.setContainerDataSource(container);

Most components that can be bound to a container allow passing it also in the constructor, in addition to using setContainerDataSource(). Creation of the container depends on its type. For some containers, such as the IndexedContainer, you need to define the contained properties (columns) as was done above, while some others determine them otherwise. The definition of a property with addContainerProperty() requires a unique property ID, type, and a default value. You can also give null. If the container of a component is replaced and the new container contains a different set of columns, such as a property with the same ID but a different data type, the component should be reinitialized. For a table or grid, it means redefining their columns.

Vaadin has a several built-in in-memory container implementations, such as IndexedContainer and BeanItemContainer, which are easy to use for setting up nonpersistent data storages. For persistent data, either the built-in SQLContainer or the JPAContainer add-on container can be used.

Adding Items and Accessing Properties

Items can be added to a container with the addItem() method. The parameterless version of the method automatically generates the item ID.

  1. // Create an item
  2. Object itemId = container.addItem();

Properties can be requested from container by first requesting an item with getItem() and then getting the properties from the item with getItemProperty().

  1. // Get the item object
  2. Item item = container.getItem(itemId);
  3. // Access a property in the item
  4. Property<String> nameProperty =
  5. item.getItemProperty("name");
  6. // Do something with the property
  7. nameProperty.setValue("box");

You can also get a property directly by the item and property ids with getContainerProperty().

  1. container.getContainerProperty(itemId, "volume").setValue(5.0);

Adding Items by Given ID

Some containers, such as IndexedContainer and HierarchicalContainer, allow adding items by a given ID, which can be any Object.

  1. Item item = container.addItem("agivenid");
  2. item.getItemProperty("name").setValue("barrel");
  3. Item.getItemProperty("volume").setValue(119.2);

Notice that the actual item is not given as a parameter to the method, only its ID, as the interface assumes that the container itself creates all the items it contains. Some container implementations can provide methods to add externally created items, and they can even assume that the item ID object is also the item itself. Lazy containers might not create the item immediately, but lazily when it is accessed by its ID.

Container Subinterfaces

The Container interface contains inner interfaces that container implementations can implement to fulfill different features required by components that present container data.

Container.Filterable

Filterable containers allow filtering the contained items by filters, as described in Filterable Containers.

Container.Hierarchical

Hierarchical containers allow representing hierarchical relationships between items and are required by the Tree and TreeTable components. The HierarchicalContainer is a built-in in-memory container for hierarchical data, and is used as the default container for the tree components. The FilesystemContainer provides access to browsing the content of a file system. Also JPAContainer is hierarchical, as described in “Hierarchical Container”.

Container.Indexed

An indexed container allows accessing items by an index number, not just their item ID. This feature is required by some components, especially Table, which needs to provide lazy access to large containers. The IndexedContainer is a basic in-memory implementation, as described in IndexedContainer.

Container.Ordered

An ordered container allows traversing the items in successive order in either direction. Most built-in containers are ordered.

Container.SimpleFilterable

This interface enables filtering a container by string matching with addContainerFilter(). The filtering is done by either searching the given string anywhere in a property value, or as its prefix.

Container.Sortable

A sortable container is required by some components that allow sorting the content, such as Table, where the user can click a column header to sort the table by the column. Some other components, such as Calendar, may require that the content is sorted to be able to display it properly. Depending on the implementation, sorting can be done only when the sort() method is called, or the container is automatically kept in order according to the last call of the method.

See the API documentation for a detailed description of the interfaces.

IndexedContainer

The IndexedContainer is an in-memory container that implements the Indexed interface to allow referencing the items by an index. IndexedContainer is used as the default container in most selection components in Vaadin.

The properties need to be defined with addContainerProperty(), which takes the property ID, type, and a default value. This must be done before any items are added to the container.

  1. // Create the container
  2. IndexedContainer container = new IndexedContainer();
  3. // Define the properties (columns)
  4. container.addContainerProperty("name", String.class, "noname");
  5. container.addContainerProperty("volume", Double.class, -1.0d);
  6. // Add some items
  7. Object content[][] = { {"jar", 2.0}, {"bottle", 0.75},
  8. {"can", 1.5}};
  9. for (Object[] row: content) {
  10. Item newItem = container.getItem(container.addItem());
  11. newItem.getItemProperty("name").setValue(row[0]);
  12. newItem.getItemProperty("volume").setValue(row[1]);
  13. }

New items are added with addItem(), which returns the item ID of the new item, or by giving the item ID as a parameter as was described earlier. Note that the Table component, which has IndexedContainer as its default container, has a conveniency addItem() method that allows adding items as object vectors containing the property values.

The container implements the Container.Indexed feature to allow accessing the item IDs by their index number, with getIdByIndex(), etc. The feature is required mainly for internal purposes of some components, such as Table, which uses it to enable lazy transmission of table data to the client-side.

BeanContainer

The BeanContainer is an in-memory container for JavaBean objects. Each contained bean is wrapped inside a BeanItem wrapper. The item properties are determined automatically by inspecting the getter and setter methods of the class. This requires that the bean class has public visibility, local classes for example are not allowed. Only beans of the same type can be added to the container.

The generic has two parameters: a bean type and an item identifier type. The item identifiers can be obtained by defining a custom resolver, using a specific item property for the IDs, or by giving item IDs explicitly. As such, it is more general than the BeanItemContainer, which uses the bean object itself as the item identifier, making the use usually simpler. Managing the item IDs makes BeanContainer more complex to use, but it is necessary in some cases where the equals() or hashCode() methods have been reimplemented in the bean.

  1. // Here is a JavaBean
  2. public class Bean implements Serializable {
  3. String name;
  4. double energy; // Energy content in kJ/100g
  5. public Bean(String name, double energy) {
  6. this.name = name;
  7. this.energy = energy;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public double getEnergy() {
  16. return energy;
  17. }
  18. public void setEnergy(double energy) {
  19. this.energy = energy;
  20. }
  21. }
  22. void basic(VerticalLayout layout) {
  23. // Create a container for such beans with
  24. // strings as item IDs.
  25. BeanContainer<String, Bean> beans =
  26. new BeanContainer<String, Bean>(Bean.class);
  27. // Use the name property as the item ID of the bean
  28. beans.setBeanIdProperty("name");
  29. // Add some beans to it
  30. beans.addBean(new Bean("Mung bean", 1452.0));
  31. beans.addBean(new Bean("Chickpea", 686.0));
  32. beans.addBean(new Bean("Lentil", 1477.0));
  33. beans.addBean(new Bean("Common bean", 129.0));
  34. beans.addBean(new Bean("Soybean", 1866.0));
  35. // Bind a table to it
  36. Table table = new Table("Beans of All Sorts", beans);
  37. layout.addComponent(table);
  38. }

See the on-line example.

To use explicit item IDs, use the methods addItem(Object, Object), addItemAfter(Object, Object, Object), and addItemAt(int, Object, Object).

It is not possible to add additional properties to the container, except properties in a nested bean.

Nested Properties

If you have a nested bean with an 1:1 relationship inside a bean type contained in a BeanContainer or BeanItemContainer, you can add its properties to the container by specifying them with addNestedContainerProperty(). The feature is defined at the level of AbstractBeanContainer.

As with the bean in a bean container, also a nested bean must have public visibility or otherwise an access exception is thrown. An intermediate reference from a bean in the bean container to a nested bean may have a null value.

For example, let us assume that we have the following two beans with the first one nested inside the second one.

  1. /** Bean to be nested */
  2. public class EqCoord implements Serializable {
  3. double rightAscension; /* In angle hours */
  4. double declination; /* In degrees */
  5. ... setters and getters for the properties ...
  6. }
  7. /** Bean referencing a nested bean */
  8. public class Star implements Serializable {
  9. String name;
  10. EqCoord equatorial; /* Nested bean */
  11. ... setters and getters for the properties ...
  12. }

See the on-line example.

After creating the container, you can declare the nested properties by specifying their property identifiers with the addNestedContainerProperty() in dot notation.

  1. // Create a container for beans
  2. BeanItemContainer<Star> stars =
  3. new BeanItemContainer<Star>(Star.class);
  4. // Declare the nested properties to be used in the container
  5. stars.addNestedContainerProperty("equatorial.rightAscension");
  6. stars.addNestedContainerProperty("equatorial.declination");
  7. // Add some items
  8. stars.addBean(new Star("Sirius", new EqCoord(6.75, 16.71611)));
  9. stars.addBean(new Star("Polaris", new EqCoord(2.52, 89.26417)));
  10. // Here the nested bean reference is null
  11. stars.addBean(new Star("Vega", null));

See the on-line example.

If you bind such a container to a Table, you probably also need to set the column headers. Notice that the entire nested bean itself is still a property in the container and would be displayed in its own column. The toString() method is used for obtaining the displayed value, which is by default an object reference. You normally do not want this, so you can hide the column with setVisibleColumns().

  1. // Put them in a table
  2. Table table = new Table("Stars", stars);
  3. table.setColumnHeader("equatorial.rightAscension", "RA");
  4. table.setColumnHeader("equatorial.declination", "Decl");
  5. table.setPageLength(table.size());
  6. // Have to set explicitly to hide the "equatorial" property
  7. table.setVisibleColumns("name",
  8. "equatorial.rightAscension", "equatorial.declination");

See the on-line example.

The resulting table is shown in Table Bound to a BeanContainer with Nested Properties.

beanitemcontainer nested beans

Table Bound to a BeanContainer with Nested Properties

The bean binding in AbstractBeanContainer normally uses the MethodProperty implementation of the Property interface to access the bean properties using the setter and getter methods. For nested properties, the NestedMethodProperty implementation is used.

Defining a Bean ID Resolver

If a bean ID resolver is set using setBeanIdResolver() or setBeanIdProperty(), the methods addBean(), addBeanAfter(), addBeanAt() and addAll() can be used to add items to the container. If one of these methods is called, the resolver is used to generate an identifier for the item (must not return null).

Note that explicit item identifiers can also be used when a resolver has been set by calling the addItem*() methods - the resolver is only used when adding beans using the addBean*() or addAll(Collection) methods.

BeanItemContainer

BeanItemContainer is a container for JavaBean objects where each bean is wrapped inside a BeanItem wrapper. The item properties are determined automatically by inspecting the getter and setter methods of the class. This requires that the bean class has public visibility, local classes for example are not allowed. Only beans of the same type can be added to the container.

BeanItemContainer is a specialized version of the BeanContainer described in BeanContainer. It uses the bean itself as the item identifier, which makes it a bit easier to use than BeanContainer in many cases. The latter is, however, needed if the bean has reimplemented the equals() or hashCode() methods.

Let us revisit the example given in BeanContainer using the BeanItemContainer.

  1. // Create a container for the beans
  2. BeanItemContainer<Bean> beans =
  3. new BeanItemContainer<Bean>(Bean.class);
  4. // Add some beans to it
  5. beans.addBean(new Bean("Mung bean", 1452.0));
  6. beans.addBean(new Bean("Chickpea", 686.0));
  7. beans.addBean(new Bean("Lentil", 1477.0));
  8. beans.addBean(new Bean("Common bean", 129.0));
  9. beans.addBean(new Bean("Soybean", 1866.0));
  10. // Bind a table to it
  11. Table table = new Table("Beans of All Sorts", beans);

See the on-line example.

It is not possible to add additional properties to a BeanItemContainer, except properties in a nested bean, as described in BeanContainer.

Iterating Over a Container

As the items in a Container are not necessarily indexed, iterating over the items has to be done using an Iterator. The getItemIds() method of Container returns a Collection of item identifiers over which you can iterate. The following example demonstrates a typical case where you iterate over the values of check boxes in a column of a Table component. The context of the example is the example used in “Table”.

  1. // Collect the results of the iteration into this string.
  2. String items = "";
  3. // Iterate over the item identifiers of the table.
  4. for (Iterator i = table.getItemIds().iterator(); i.hasNext();) {
  5. // Get the current item identifier, which is an integer.
  6. int iid = (Integer) i.next();
  7. // Now get the actual item from the table.
  8. Item item = table.getItem(iid);
  9. // And now we can get to the actual checkbox object.
  10. Button button = (Button)
  11. (item.getItemProperty("ismember").getValue());
  12. // If the checkbox is selected.
  13. if ((Boolean)button.getValue() == true) {
  14. // Do something with the selected item; collect the
  15. // first names in a string.
  16. items += item.getItemProperty("First Name")
  17. .getValue() + " ";
  18. }
  19. }
  20. // Do something with the results; display the selected items.
  21. layout.addComponent (new Label("Selected items: " + items));

Notice that the getItemIds() returns an unmodifiable collection, so the Container may not be modified during iteration. You can not, for example, remove items from the Container during iteration. The modification includes modification in another thread. If the Container is modified during iteration, a ConcurrentModificationException is thrown and the iterator may be left in an undefined state.

GeneratedPropertyContainer

GeneratedPropertyContainer is a container wrapper that allows defining generated values for properties (columns). The generated properties can shadow properties with the same IDs in the wrapped container. Removing a property from the wrapper hides it.

The container is especially useful with Grid, which does not support generated columns or hiding columns like Table does.

Wrapping a Container

A container to be wrapped must be a Container.Indexed. It can optionally also implement Container.Sortable or Container.Filterable to enable sorting and filtering the container, respectively.

For example, let us consider the following container with some regular columns:

  1. IndexedContainer container = new IndexedContainer();
  2. container.addContainerProperty("firstname", String.class, null);
  3. container.addContainerProperty("lastname", String.class, null);
  4. container.addContainerProperty("born", Integer.class, null);
  5. container.addContainerProperty("died", Integer.class, null);
  6. // Wrap it
  7. GeneratedPropertyContainer gpcontainer =
  8. new GeneratedPropertyContainer(container);

Generated Properties

Now, you can add generated properties in the container with addGeneratedProperty() by specifying a property ID and a PropertyValueGenerator. The method takes the ID of the generated property as first parameter; you can use a same ID as in the wrapped container to shadow its properties.

You need to implement getType(), which must return the class object of the value type of the property, and getValue(), which returns the property value for the given item. The item ID and the property ID of the generated property are also given in case they are needed. You can access other properties of the item to compute the property value.

  1. gpcontainer.addGeneratedProperty("lived",
  2. new PropertyValueGenerator<Integer>() {
  3. @Override
  4. public Integer getValue(Item item, Object itemId,
  5. Object propertyId) {
  6. int born = (Integer)
  7. item.getItemProperty("born").getValue();
  8. int died = (Integer)
  9. item.getItemProperty("died").getValue();
  10. return Integer.valueOf(died - born);
  11. }
  12. @Override
  13. public Class<Integer> getType() {
  14. return Integer.class;
  15. }
  16. });

You can access other items in the container, also their generated properties, although you should beware of accidental recursion.

Using GeneratedPropertyContainer

Finally, you need to bind the GeneratedPropertyContainer to the component instead of the wrapped container.

  1. Grid grid = new Grid(gpcontainer);

When using GeneratedPropertyContainer in Grid, notice that generated columns are read-only, so you can not add grid rows with addRow(). In editable mode, editor fields are not generated for generated columns.

Sorting

Even though the GeneratedPropertyContainer implements Container.Sortable, the wrapped container must also support it or otherwise sorting is disabled. Also, the generated properties are not normally sortable, but require special handling to enable sorting.

Filterable Containers

Containers that implement the Container.Filterable interface can be filtered. For example, the built-in IndexedContainer and the bean item containers implement it. Filtering is typically used for filtering the content of a Table.

Filters implement the Filter interface and you add them to a filterable container with the addContainerFilter() method. Container items that pass the filter condition are kept and shown in the filterable component.

  1. Filter filter = new SimpleStringFilter("name",
  2. "Douglas", true, false);
  3. table.addContainerFilter(filter);

See the on-line example.

If multiple filters are added to a container, they are evaluated using the logical AND operator so that only items that are passed by all the filters are kept.

Atomic and Composite Filters

Filters can be classified as atomic and composite. Atomic filters, such as SimpleStringFilter, define a single condition, usually for a specific container property. Composite filters make filtering decisions based on the result of one or more other filters. The built-in composite filters implement the logical operators AND, OR, or NOT.

For example, the following composite filter would filter out items where the name property contains the name “Douglas” somewhere or where the age property has value less than 42. The properties must have String and Integer types, respectively.

  1. filter = new Or(new SimpleStringFilter("name",
  2. "Douglas", true, false),
  3. new Compare.Less("age", 42));

Built-In Filter Types

The built-in filter types are the following:

SimpleStringFilter

Passes items where the specified property, that must be of String type, contains the given filterString as a substring. If ignoreCase is true, the search is case insensitive. If the onlyMatchPrefix is true, the substring may only be in the beginning of the string, otherwise it may be elsewhere as well.

IsNull

Passes items where the specified property has null value. For in-memory filtering, a simple == check is performed. For other containers, the comparison implementation is container dependent, but should correspond to the in-memory null check.

Equal, Greater, Less, GreaterOrEqual, and LessOrEqual

The comparison filter implementations compare the specified property value to the given constant and pass items for which the comparison result is true. The comparison operators are included in the abstract Compare class.

For the Equal filter, the equals() method for the property is used in built-in in-memory containers. In other types of containers, the comparison is container dependent and may use, for example, database comparison operations.

For the other filters, the property value type must implement the Comparable interface to work with the built-in in-memory containers. Again for the other types of containers, the comparison is container dependent.

And and Or

These logical operator filters are composite filters that combine multiple other filters.

Not

The logical unary operator filter negates which items are passed by the filter given as the parameter.

Implementing Custom Filters

A custom filter needs to implement the Container.Filter interface.

A filter can use a single or multiple properties for the filtering logic. The properties used by the filter must be returned with the appliesToProperty() method. If the filter applies to a user-defined property or properties, it is customary to give the properties as the first argument for the constructor of the filter.

  1. class MyCustomFilter implements Container.Filter {
  2. protected String propertyId;
  3. protected String regex;
  4. public MyCustomFilter(String propertyId, String regex) {
  5. this.propertyId = propertyId;
  6. this.regex = regex;
  7. }
  8. /** Tells if this filter works on the given property. */
  9. @Override
  10. public boolean appliesToProperty(Object propertyId) {
  11. return propertyId != null &&
  12. propertyId.equals(this.propertyId);
  13. }

See the on-line example.

The actual filtering logic is done in the passesFilter() method, which simply returns true if the item should pass the filter and false if it should be filtered out.

  1. /** Apply the filter on an item to check if it passes. */
  2. @Override
  3. public boolean passesFilter(Object itemId, Item item)
  4. throws UnsupportedOperationException {
  5. // Acquire the relevant property from the item object
  6. Property p = item.getItemProperty(propertyId);
  7. // Should always check validity
  8. if (p == null || !p.getType().equals(String.class))
  9. return false;
  10. String value = (String) p.getValue();
  11. // The actual filter logic
  12. return value.matches(regex);
  13. }
  14. }

See the on-line example.

You can use such a custom filter just like any other:

  1. c.addContainerFilter(
  2. new MyCustomFilter("Name", (String) tf.getValue()));

See the on-line example.