假设我有一个Grid<Person>
和一些person.getStatus()
它返回一个枚举
enum Status {
SINGLE, MARRIED, DIVORCED
}
我想根据此枚举的值为网格的列着色。
如何做到这一点?
最佳答案
在瓦丁 14
根据数据设置网格行样式
首先,您需要为行设置 CSS 类名生成器。这会将 CSS 类名称添加到 Grid 创建的 td 元素中。生成器函数接收您的项目,如果您不想为某些行添加类名,则应返回 String 形式的 CSS 类名或 null。可以从生成器返回多个类名,以空格分隔。
grid.setClassNameGenerator(person -> {
if (person.getStatus() == Status.DIVORCED || person.getStatus() == Status.SINGLE) {
return "my-style-1";
} else {
return "my-style-2";
}
});
要根据 CSS 类名称更改样式,您需要为 Grid 创建主题。
在frontend/styles
文件夹中添加styles.css
。
td.my-style-1 {
background-color: black;
color: hotpink;
}
td.my-style-2 {
background-color: hotpink;
color: black;
}
并将样式包含到您的应用中。
@Route
@CssImport(value = "./styles/styles.css", themeFor = "vaadin-grid")
public class MainView extends VerticalLayout {
// your code for grid
}
根据数据设置网格单元格样式
CSS 样式导入和创建的方式与行样式相同,但使用的 Grid API 不同。
对于单元格,您应该使用列类名称生成器:
grid.getColumnByKey("status").setClassNameGenerator(person -> {
if (person.getStatus() == Status.SINGLE) {
return "my-style-3";
}
return null;
});
关于java - 如何根据 Vaadin 14 中的数据为网格的行或单元格着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60464437/