【问题标题】:How to set a style class for a column in Vaadin Grid?如何为 Vaadin Grid 中的列设置样式类?
【发布时间】:2025-03-07 17:55:01
【问题描述】:

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

【问题讨论】:

    标签: vaadin vaadin7 vaadin-grid


    【解决方案1】:

    您只能为网格设置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://*.com/a/36398300/952135
     * @author http://*.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);
        }
    
    }
    
    最近更新 更多