Search code examples
vaadinvaadin7vaadin-grid

How to make a sequential number columns in Vaadin


I created a table in vaadin. I am selecting columns from the database. I need a column which sequentially gives number to every row.

I am using the

  Table table = new Table();

For Grid:

 GeneratedPropertyContainer wrappingContainer = new GeneratedPropertyContainer(container);
            wrappingContainer.addGeneratedProperty("rowHeader", new PropertyValueGenerator<Long>();

 table.setContainerDataSource(wrappingContainer);
        table.setColumnOrder("rowHeader", "name", "surname");

  layout.addComponent(table);

Solution

  • Use a generated Column for that:

    table.addGeneratedColumn("index", new ColumnGenerator(){
        @Override
        public Object generateCell(final Table source, final Object itemId, final Object columnId)
        {
            Container.Indexed container = (Container.Indexed) source.getContainerDataSource();
            return Integer.toString(container.indexOfId(itemId));
        }
    });
    
    // add it to the start of the visible columns
    table.setVisibleColumns("index", /* other columns ... */);
    

    You get the row number from the container. The table though has to work with a Container that implements the Indexed sub-interface, for example BeanItemContainer or IndexedContainer.

    This is what you do using the Grid:

    // the GeneratedPropertyContainer is a decorator for the original container
    final GeneratedPropertyContainer gpc = new GeneratedPropertyContainer(container);
    grid.setContainerDataSource(gpc);
    gpc.addGeneratedProperty("index", new PropertyValueGenerator<String>(){
        @Override
        public String getValue(final Item item, final Object itemId, final Object propertyId)
        {
            // get the index from the original container
            final Container.Indexed indexContainer = (Container.Indexed) container;
            return Integer.toString(indexContainer.indexOfId(itemId));
        }
    
        @Override
        public Class<String> getType()
        {
            return String.class;
        }
    });
    
    // ...
    
    grid.setColumnOrder("index", /* the other property IDs... */);
    

    If you use a PropertyValueGenerator<Long> you need to set a NumberRenderer for that type. grid.getColumn("index").setRenderer(new NumberRenderer("%d")); will do the trick.