vaadin - 如何为 Vaadin Grid 中的列设置样式类?

标签 vaadin vaadin7 vaadin-grid

我想为 Grid 中的列分配样式类。 Column 类不提供其他 Vaadin 组件所提供的 addStyleName 方法。有办法做到吗?

最佳答案

您只能为网格设置 CellStyleGeneratorRowStyleGenerator。要为列设置类,您必须执行以下操作:

grid.setCellStyleGenerator(new CellStyleGenerator() {
    @Override
    public String getStyle(CellReference cell) {
        if ("myProperty".equals(cell.getPropertyId()))
            return "my-style";
        else
            return null;
    }
});

单个 Grid 只能有单个 CellStyleGenerator。我经常有复杂的代码来配置网格,并且我逐列配置它。我使用这个实用程序类,它使我能够这样做(需要 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);
    }

}

关于vaadin - 如何为 Vaadin Grid 中的列设置样式类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36398299/

相关文章:

data-binding - Vaadin 8 Binder 中相关计算属性的自动更新显示

java - 使用逗号分隔符将 double 转换为 2 位小数

vaadin - Vaadin 13 Grid 中是否有一个 "Select All"checkbok(即使有过滤条件也能工作,甚至有些数据不在缓存中?)

java - 可扩展网格 Vaadin UI

java - 具有生成的属性和排序的 Vaadin 网格

gwt - Vaadin - 总是需要 GWT 依赖?

java - 为什么 Vaadin 14 中包含的 Guava 库没有出现在我的项目的类路径中?

java - 使用 Vaadin 将 Maven 项目部署到 Tomcat

java - 推送后如何更新 Vaadin Grid?

java - 如何更新 Vaadin 网格上的项目而不显式放置所有字段?