Styling Individuals CELLS in Vaadin 8 Grid

I understand that the StyleGenerator is applied via columns now, but how do I apply a different color to different cells in a grid’s row? See attached image.

The post [here]
(https://stackoverflow.com/a/48296704) says you can use a switch statement in the StyleGenerator, but this applies to ALL cells in the row. I want to be able to use DIFFERENT colors for DIFFERENT cells, in the SAME row.

grid
  .addColumn(Stock::getValue1)
  .setCaption("Value1")
  .setStyleGenerator(stockRow -> {
    switch (stockRow.getValue1()) {
      case "1": return "red";
      case "3": return "yellow";
      case "5": return "green";
      default: return null;
    }
  });

What’s the solution?

17196401.png

Anybody?

Check chapter “Generating Row or Cell Styles” here:

https://vaadin.com/docs/v8/framework/components/components-grid.html

Generating Cell Styles

You set a StyleGenerator to a grid with setStyleGenerator(). The getStyle() method gets a CellReference, which contains various information about the cell and a reference to the grid, and should return a style name or null if no style is generated.

For example, to add a style name to a specific column, you can match on the column as follows:

// Static style based on column
bornColumn.setStyleGenerator(person -> "rightalign");

You could then style the cells with a CSS rule as follows:

.v-grid-cell.rightalign {
    text-align: right;
}

Thanks Tatu,

But I believe I addressed this in my original question. Your solution seems to style ALL cells in a column the SAME.

If I do

bornColumn.setStyleGenerator(person -> "rightalign");

then every single cell in bornColumn gets the style rightalign. But what if I want only the cell in row #1 of bornColumn to be right-aligned, and I want cell in row #2 in bornColumn to be left-aligned?

Perhaps you missed my screenshot in my original question? I don’t see how your suggestion accomplishes this.

Thank you.

Your style generator looks correct

grid
  .addColumn(Stock::getValue1)
  .setCaption("Value1")
  .setStyleGenerator(stockRow -> {
    switch (stockRow.getValue1()) {
      case "1": return "red";
      case "3": return "yellow";
      case "5": return "green";
      default: return null;
    }
  });

What you need is corresponding styles in your theme mixin:

.v-grid-cell.red {
    color: red;
}
 
.v-grid-cell.yellow {
    color: yellow;
}
 
.v-grid-cell.green {
    color: green;
}

Ah, I understand now. Got it working :slight_smile:

Thank you kindly, Tatu. +1

Hi,
is there any way to set several styles at time using StyleGenerator?
For examle, I need some cells to have “number” style, but if value is zero add “number” + “red” styles
so DOM element will have both of styles
or I need to make some style like “red-numer”?