我希望将样式类分配给Grid
中的列。 Column
类不提供其他Vaadin组件所执行的addStyleName
方法。有办法吗?
答案 0 :(得分:2)
您只能为网格设置CellStyleGenerator
或RowStyleGenerator
。要为列设置类,必须执行以下操作:
grid.setCellStyleGenerator(new CellStyleGenerator() {
@Override
public String getStyle(CellReference cell) {
if ("myProperty".equals(cell.getPropertyId()))
return "my-style";
else
return null;
}
});
单CellStyleGenerator
只能有一个Grid
。我经常有复杂的代码来配置网格,我逐列配置它。我使用这个实用程序类,这使我能够这样做(需要Java8):
/**
* A {@link CellStyleGenerator}, that enables you to set <code>CellStyleGenerator</code>
* independently for each column. It also has a shorthand method to set a fixed style
* class for a column, which Vaadin currently does not allow to (as of Vaadin 7.6).
*
* For more information, see http://stackoverflow.com/a/36398300/952135
* @author http://stackoverflow.com/users/952135
*/
public class EasyCellStyleGenerator implements CellStyleGenerator {
private Map<Object, List<CellStyleGenerator>> generators;
@Override
public String getStyle(CellReference cellReference) {
if (generators != null) {
List<CellStyleGenerator> gens = generators.get(cellReference.getPropertyId());
if (gens != null)
return gens.stream()
.map(gen -> gen.getStyle(cellReference))
.filter(s -> s != null)
.collect(Collectors.joining(" "));
}
return null;
}
/**
* Adds a generator for a column. Allows generating different style for each cell,
* but is called only for the given column.
*/
public void addColumnCellStyleGenerator(Object propertyId,
CellStyleGenerator generator) {
if (generators == null) // lazy init of map
generators = new HashMap<>();
generators.computeIfAbsent(propertyId, k->new ArrayList<>()).add(generator);
}
/**
* Sets a fixed style class(es), that will be used for all cells of this column.
*/
public void addColumnFixedStyle(Object propertyId, String styleClasses) {
addColumnCellStyleGenerator(propertyId, cellReference -> styleClasses);
}
}