Search code examples
gridvaadin7

displaying multiple components within a cell of vaadin grid


Is there any way I can display multiple components(like CheckBox, Label etc.) to a single cell of a Vaadin Grid? The Grid displays data populated dynamically by a GeneratedPropertyContainer.

Thanks in advance.


Solution

  • If you search the Vaadin directory you will find a few extensions, such as ComponentRenderer add-on which allow you to have such features in a somewhat painless way. Below you can see a code sample based on Vaadin v7.7.3 and v1.0.2 of the before-mentioned add-on. Please remember to update and recompile your widgetset.

    public class GridWithMultiComponentRenderer extends VerticalLayout {
    
        private static final String BUTTONS_ID = "buttons";
    
        public GridWithMultiComponentRenderer() {
            // basic grid setup
            Grid grid = new Grid(new BeanItemContainer<>(Person.class));
            grid.setSizeFull();
            addComponent(grid);
    
            // add the decorator
            ComponentGridDecorator<Person> gridDecorator = new ComponentGridDecorator<>(grid, Person.class);
    
            // generate the column which will display the components
            gridDecorator.addComponentColumn(BUTTONS_ID, person -> new HorizontalLayout(
                    new Button("Get name", event -> Notification.show(person.getName())),
                    new Button("Get surname", event -> Notification.show(person.getSurname())),
                    new Button("Get age", event -> Notification.show(String.valueOf(person.getAge())))
            ));
    
            // set column order
            grid.setColumns("name", "surname", "age", BUTTONS_ID);
    
            // add some dummy data
            Random random = new Random();
            for (int i = 0; i < 10; i++) {
                gridDecorator.add(new Person("Name " + i, "Surname " + i, random.nextInt(99) + 1));
            }
        }
    
        // POJO for simple binding
        public static class Person {
            private String name;
            private String surname;
            private int age;
    
            public Person(String name, String surname, int age) {
                this.name = name;
                this.surname = surname;
                this.age = age;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public String getSurname() {
                return surname;
            }
    
            public void setSurname(String surname) {
                this.surname = surname;
            }
    
            public int getAge() {
                return age;
            }
    
            public void setAge(int age) {
                this.age = age;
            }
        }
    }
    

    Result:

    multiple components in grid column