更改网格中单元格的颜色(Vaadin)
Change color of cell in Grid (Vaadin)
我在 Grid
中使用 BeanItemContainer
来显示我的数据。我需要根据单元格中的数据分别为每个单元格着色。
Book of Vaadin 中的 section about the Grid 在 Generating Cell Styles 小节中对此进行了解释:
You set a CellStyleGenerator
to a grid with setCellStyleGenerator()
. 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 property ID of the column as follows:
grid.setCellStyleGenerator(cellRef -> // Java 8
"born".equals(cellRef.getPropertyId())?
"rightalign" : null);
You could then style the cells with a CSS rule as follows:
.v-grid-cell.rightalign {
text-align: right;
}
还有一种方法,100% 动态,没有样式文件。
grid.addColumn(TemplateRenderer.<MyObj> of("<div style$=\"background-color: [[item.color]];\">[[item.duration]]</div>")
.withProperty("color", MyObj::getDurationColor)
.withProperty("duration", MyObj::getDurationMin)).setHeader("Duration");
在这种情况下,颜色会随着持续时间的增加而变得更浓。
public String getDurationColor() {
long latency = durationMin;
if (latency > 255) latency = 255;
return "#ff" + Long.toHexString(255-latency) + Long.toHexString(255-latency);
}
我在 Grid
中使用 BeanItemContainer
来显示我的数据。我需要根据单元格中的数据分别为每个单元格着色。
Book of Vaadin 中的 section about the Grid 在 Generating Cell Styles 小节中对此进行了解释:
You set a
CellStyleGenerator
to a grid withsetCellStyleGenerator()
. ThegetStyle()
method gets aCellReference
, which contains various information about the cell and a reference to the grid, and should return a style name ornull
if no style is generated.For example, to add a style name to a specific column, you can match on the property ID of the column as follows:
grid.setCellStyleGenerator(cellRef -> // Java 8 "born".equals(cellRef.getPropertyId())? "rightalign" : null);
You could then style the cells with a CSS rule as follows:
.v-grid-cell.rightalign { text-align: right; }
还有一种方法,100% 动态,没有样式文件。
grid.addColumn(TemplateRenderer.<MyObj> of("<div style$=\"background-color: [[item.color]];\">[[item.duration]]</div>")
.withProperty("color", MyObj::getDurationColor)
.withProperty("duration", MyObj::getDurationMin)).setHeader("Duration");
在这种情况下,颜色会随着持续时间的增加而变得更浓。
public String getDurationColor() {
long latency = durationMin;
if (latency > 255) latency = 255;
return "#ff" + Long.toHexString(255-latency) + Long.toHexString(255-latency);
}