如何在Vaadin Grid中为列设置样式类?

时间:2016-04-04 08:55:57

标签: vaadin vaadin7 vaadin-grid

我希望将样式类分配给Grid中的列。 Column类不提供其他Vaadin组件所执行的addStyleName方法。有办法吗?

1 个答案:

答案 0 :(得分:2)

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

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);
    }

}
相关问题