Change row or column color based on color selection from ColorPicker

How do I change the table row and column color based on the value from ColorPicker?

1 Like

Hi,

You can use Table.StyleProvider and dynamically injected CSS.

We add StyleProvider to Table that will return CSS style name for color defined in entity:


clientsTable.addStyleProvider((entity, property) -> {
    if ("color".equals(property) && entity.getColor() != null) {
        return "colored-cell-" + entity.getColor();
    }
    return null;
});

These colored-cell- CSS classes will be injected on the fly:


protected void injectColorCss(String color) {
    Page.Styles styles = Page.getCurrent().getStyles();
    styles.add(String.format(
            ".colored-cell-%s { background-color: #%s; }",
            color, color));
}

We can apply color on value change of ColorPicker:


colorPicker.addValueChangeListener(e -> {
    Client client = clientsTable.getSingleSelected();
    if (client != null) {
        client.setColor((String) e.getValue());
        // inject new CSS
        injectColorCss((String) e.getValue());
        // repaint table
        clientsTable.repaint();
    }
});

I’ve created a small demo project where you can see this approach in action. See GitHub - cuba-labs/colored-cells-table

If you don’t want to inject CSS on the fly I recommend that you create predefined CSS rules and switch ColorPicker to Swatches mode with only small amount of predefined colors instead of unlimited palette.

Sorry for replying to this old topic, but there’s an issue that should be noted in this approach…

If the new style is being added to the Page styles inside the addStyleProvider delegate, Vaadin raises the following exception:

ERROR [http-nio-8080-exec-4/oslint/admin] com.haulmont.cuba.web.gui.components.WebAbstractTable - Uncautch exception in Table StyleProvider
java.lang.IllegalStateException: A connector should not be marked as dirty while a response is being written.

This approach works as long as all the styles are injected in the page outside the style provider.

P.

1 Like