Using Grid with inline data

Instead of using a Vaadin Container as explained in Using Grid With a Container, you can also directly add simple inline data to Grid without directly using a Container.

After creating a Grid instance, the first thing you need to do is to define the columns that should be shown. You an also define the types of the data in each column - Grid will expect String data in each column unless you do this.

Java

  1. grid.addColumn("Name").setSortable(true);
  2. grid.addColumn("Score", Integer.class);

The columns will be shown in the order they are added. The addColumn method does also return the created Column instance, so you can go ahead and configure the column right away if you want to.

When you have added all columns, you can add data using the addRow(Object…​) method.

Java

  1. grid.addRow("Alice", 15);
  2. grid.addRow("Bob", -7);
  3. grid.addRow("Carol", 8);
  4. grid.addRow("Dan", 0);
  5. grid.addRow("Eve", 20);

The order of the arguments to addRow should match the order in which the columns are shown. It is recommended to only use addRow when initializing Grid, since later on e.g. setColumnOrder(Object…​) might have been used to change the order, causing unintended behavior.

Grid will still manage a Container instance for you behind the scenes, so you can still use Grid API that is based on Property or Item from the Container API. One particularly useful feature is that each added row will get an Integer item id, counting up starting from 1. This means that you can e.g. select the second row in this way:

Java

  1. grid.select(2);

Full example

Putting all these pieces together, we end up with this class.

Java

  1. import com.vaadin.annotations.Theme;
  2. import com.vaadin.server.VaadinRequest;
  3. import com.vaadin.shared.ui.grid.HeightMode;
  4. import com.vaadin.ui.Grid;
  5. import com.vaadin.ui.UI;
  6. @Theme("valo")
  7. public class ShowingInlineDataInGrid extends UI {
  8. @Override
  9. protected void init(VaadinRequest request) {
  10. final Grid grid = new Grid();
  11. grid.addColumn("Name").setSortable(true);
  12. grid.addColumn("Score", Integer.class);
  13. grid.addRow("Alice", 15);
  14. grid.addRow("Bob", -7);
  15. grid.addRow("Carol", 8);
  16. grid.addRow("Dan", 0);
  17. grid.addRow("Eve", 20);
  18. grid.select(2);
  19. grid.setHeightByRows(grid.getContainerDataSource().size());
  20. grid.setHeightMode(HeightMode.ROW);
  21. setContent(grid);
  22. }
  23. }