Showing data in Grid

Grid lazy-loads data from a Container instance. There are different container implementations that e.g. fetch data from a database or use a list of Java objects. Assuming you already have code that initializes a Container, this is all that is needed for showing a Grid with the data from your container.

Java

  1. import com.vaadin.server.VaadinRequest;
  2. import com.vaadin.ui.Grid;
  3. import com.vaadin.ui.UI;
  4. public class UsingGridWithAContainer extends UI {
  5. @Override
  6. protected void init(VaadinRequest request) {
  7. Grid grid = new Grid();
  8. grid.setContainerDataSource(GridExampleHelper.createContainer());
  9. setContent(grid);
  10. }
  11. }

The container in this example contains three properties; name, count and amount. You can configure the columns in Grid using the property ids to do things like setting the column caption, removing a column or changing the order of the visible columns.

Java

  1. protected void init(VaadinRequest request) {
  2. Grid grid = new Grid();
  3. grid.setContainerDataSource(GridExampleHelper.createContainer());
  4. grid.getColumn("name").setHeaderCaption("Bean name");
  5. grid.removeColumn("count");
  6. grid.setColumnOrder("name", "amount");
  7. setContent(grid);
  8. }

This is really all that is needed to get started with Grid.

For reference, this is how the example container is implemented.

Java

  1. public class GridExampleBean {
  2. private String name;
  3. private int count;
  4. private double amount;
  5. public GridExampleBean() {
  6. }
  7. public GridExampleBean(String name, int count, double amount) {
  8. this.name = name;
  9. this.count = count;
  10. this.amount = amount;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public int getCount() {
  16. return count;
  17. }
  18. public double getAmount() {
  19. return amount;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public void setCount(int count) {
  25. this.count = count;
  26. }
  27. public void setAmount(double amount) {
  28. this.amount = amount;
  29. }
  30. }

Java

  1. import com.vaadin.data.util.BeanItemContainer;
  2. public class GridExampleHelper {
  3. public static BeanItemContainer<GridExampleBean> createContainer() {
  4. BeanItemContainer<GridExampleBean> container = new BeanItemContainer<GridExampleBean>(GridExampleBean.class);
  5. for (int i = 0; i < 1000; i++) {
  6. container.addItem(new GridExampleBean("Bean " + i, i * i, i / 10d));
  7. }
  8. return container;
  9. }
  10. }