How to color a row or cell of a grid depending on it's data in Vaadin 14

yaseco :

Suppose I have a Grid<Person> and some person.getStatus() which returns an Enum

enum Status {
SINGLE, MARRIED, DIVORCED
}

I'd like to color the grid's column according to this enum's value.

How can it be done?

vivid_voidgroup :

In Vaadin 14

Style a Grid row based on data

First, you need to set the CSS class name generator for the row. This will add the CSS class name to the td elements created by Grid. The generator function receives your item and you should return a CSS class name as a String or null if you don't want to add a class name for certain rows. Multiple class names can be returned from the generator as space-separated.

grid.setClassNameGenerator(person -> {
    if (person.getStatus() == Status.DIVORCED || person.getStatus() == Status.SINGLE) {
        return "my-style-1";
    } else {
        return "my-style-2";
    }
});

To change the style based on the CSS class names, you need to create a theme for Grid.

In frontend/styles folder add styles.css.

td.my-style-1 {
    background-color: black;
    color: hotpink;
}

td.my-style-2 {
    background-color: hotpink;
    color: black;
}

And include the style to your app.

@Route
@CssImport(value = "./styles/styles.css", themeFor = "vaadin-grid")
public class MainView extends VerticalLayout {
// your code for grid
}

Style a Grid cell based on data

The CSS style importing and creating is done the same way as with row styling, but the Grid API used is different.

For a cell, you should use the column class name generator:

grid.getColumnByKey("status").setClassNameGenerator(person -> {
    if (person.getStatus() == Status.SINGLE) {
        return "my-style-3";
    }
    return null;
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17824&siteId=1