Grid: how to change color of an individual cell?

Hi,

How do you change background color of an individual cells in new Grid component?

With a
Grid.CellStyleGenerator
.

Hi Marko,

Thanks for a link.

I tried something like this:

[code]

grid.setCellStyleGenerator(cellRef → “example”.equals(cellRef.getPropertyId())?
“rightalign” : null);
[/code]Where,
“example” : is a column based on the property id

and css was something like this:

.v-grid-cell.rightalign { background-color: #ffff00; } How do you change color of only an individual cell and not entire column?

For example,

Cell A1 (Row 1, Column 1)
Cell D2 (Row 4, Column 2)

The cellRef there is a
Grid.CellReference
object, which contains the item and property ID of the cell, among other things.

Thanks for the reference.

I don’t know how to make this work. Could you please give simple example for coloring ?

Cell
A1
(Row 1, Column 1)
Cell
D2
(Row 4, Column 2)

I added a bit more logic to the
CellStyleGenerator example
. Now it also uses the cell property value for the logic.

Using the item ID and property ID is easiest, but that depends on what kind of container and IDs you are using. You can use the IDs in many ways. For example, if you want to test the row number, you could do
if (grid.getContainerDataSource().indexOfId(cellRef.itemId()) == 3) return “red”;
. There’s no similar method to get the index of a column (property).

Thanks Marko.

Let me experiment this …
looks nice that you put more logic in to the CellSytleGenerator example. :slight_smile:

The problem with this approach ist, that you need to provide a CSS style for each color you want to render. Some time ago I tried the Grid with Renderers and tried to put a color on every cell programmatically. I put it together quickly, in reality you wouldnt encode the color and cell text using a single string. But maybe it will get you started:

Client side:

[code]
package project.widgetset.client.grid.renderer;

import com.vaadin.client.renderers.Renderer;
import com.vaadin.client.widget.grid.RendererCellReference;

public class ColorRenderer implements Renderer
{

@Override
public void render(RendererCellReference cell, String text)
{
    if (text != null && text.length() > 0 && text.contains("|"))
    {
        String color = text.substring(text.indexOf("|") + 1);
        cell.getElement().getStyle().setBackgroundColor(color);
        text = text.substring(0, text.indexOf("|"));
    }
    else
    {
        cell.getElement().getStyle().clearBackgroundColor();
    }

    cell.getElement().setInnerText(text);
}

}

package project.widgetset.client.grid.renderer;

import com.vaadin.client.connectors.AbstractRendererConnector;
import com.vaadin.shared.ui.Connect;

@SuppressWarnings(“serial”)
@Connect(project.grid_renderer.ColorRenderer.class)
public class ColorRendererConnector extends AbstractRendererConnector
{

@Override
public ColorRenderer getRenderer()
{
    return (ColorRenderer) super.getRenderer();
}

}
[/code]Server side:

[code]
package project.grid_renderer;

import com.vaadin.ui.Grid.AbstractRenderer;

@SuppressWarnings(“serial”)
public class ColorRenderer extends AbstractRenderer
{

public ColorRenderer()
{
    super(String.class);
}

}
[/code]Now when filling the cells you can do something like:

    protected String generateColorHexString(double value)
    {
        java.awt.Color color = getColor(value);
        int red = color.getRed();
        int green = color.getGreen();
        int blue = color.getBlue();
        String format = StringUtil.format("%s%s%s", toHex(red), toHex(green), toHex(blue));
        // log.info("color:" + format + " value:" + value);
        return format;
    }

    public java.awt.Color getColor(double power)
    {
        double H = power * 0.4; // Hue (note 0.4 = Green, see huge chart below)
        double S = 0.9; // Saturation
        double B = 0.9; // Brightness

        return java.awt.Color.getHSBColor((float) H, (float) S, (float) B);
    }

    private String toHex(int i)
    {
        String greenHex = Integer.toHexString(i);
        if (greenHex.equals("0"))
        {
            greenHex = "00";
        }
        return greenHex;
    }


When filling:
.......
     String hexString = generateColorHexString(value);
     Property containerProperty = container.getContainerProperty(rowId, map.get(workingDay));
     containerProperty.setValue(StringUtil.format("%s|#%s", textContent, hexString));

Hope it helps!

Thanks Florian.

I think this is a better approach, rather than testing an individual cell.
Do we have to create a new
vaadin widget
for this?
I mean how do I embed this in my existing project?

You simply put the client side code in your widgetset.client directory, and the server-side code in some other project directory (make sure the connector references the server-side), recompile your widgetset and use the renderer.

Thanks for your response.

Somehow it complains that:


StringUtil
cannot be resolved

even if I’ve imported

import com.vaadin.sass.internal.util.StringUtil;

StringUtil is my own implementation. You can use String.format()

And also dont take this example literally… i tried to get colors between green and red, determined by double values from 0 to 1. But I don’t think you need it…And its very unfinished. You can just set the Renderer and set the columns value in the container to e.g. “asdf|#ff00ff”…

Thanks for the suggestion. But now I am stuck with filling the grid cells, especially these two final lines:


Property containerProperty = container.getContainerProperty(rowId, map.get(workingDay));
containerProperty.setValue(String.format(“%s|#%s”, textContent, hexString)); */

Earlier, I got the colors for a column by doing this:

      grid.setCellStyleGenerator(cellRef -> {
            if ("exampleA".equals(cellRef.getPropertyId())) {
                if ((cellRef.getValue()=="A1"))
                    return "rightalign supercell2";
                else if ((cellRef.getValue()=="A2"))
                    return "supercell3";
                else return "rightalign";
            } else
                return null;
        });

css file

.v-grid-cell.supercell2 {
    background: red;
}

.v-grid-cell.supercell3 {
    background: green;
}

This part is also from my custom implementation. You need to set the string of the column which you want to set the background color of. If you use the Grid default container with addRow functionality, you would set the string for example to “A1|#ff00ff” to set the color.
For the alignment you still need a CellStyleGenerator.

Thanks for your answer.
Perphaps, I don’t know how to get a cell of a specific column and set the string to “A1|#ff00ff” :frowning:

Alright, then I would point you to
https://vaadin.com/blog/-/blogs/using-vaadin-grid
and
https://vaadin.com/book/-/page/datamodel.container.html

Hi Florian,

Thanks for your links. I tried doing something like this:
String hexString = generateColorHexString(value); grid.getColumn("Example1").getPropertyId().equals("A1|#ff00ff"); grid.setStyleName(hexString); Unfortunately, the string "
A1
" in column
Example1
does not change the color.
I guess this is not the way it should be done?