Search code examples
javavaadinvaadin-gridvaadin8

setStyleGenerator depends on cell value


I need to know how to use grid's setStyleGenerator for each cell depends on its value.

For example: for number column, I want every minus value (less than zero) has red text color.

I already know how to setting style for entire column.

addColumn(...).setStyleGenerator(...)

Solution

  • Assuming your grid bean (lets call it GridExampleBean for now) has a property/field of number, the following should accomplish adding the style name of "red" to your grid cell when that grid row's item numbner property is less than zero:

    Grid<GridExampleBean> grid = new Grid<GridExampleBean>(GridExampleBean.class);
    // you can also use the getColumn method too :  grid.getColumn("number").
    grid.addColumn(...)
            .setStyleGenerator((StyleGenerator<GridExampleBean>) item -> {
        if (item.getNumber() < 0) {
            return "red";
        }
        return "notRed";
    });