GXT - How to set the grid cell background color

Problem:
Do you need to set dynamically or programmatically the background color for some grid cells, let's say based on the value that they contain or other criteria ?

Note: The similar problem we solved using the GWT-Ext here.


Solution:
In a nutshell the solution is like you might be thinking too, the cell renderer. And doing this will get ready to write the code:

ColumnConfig typeCol = new ColumnConfig("Type");

typeCol.setRenderer(new GridCellRenderer<BaseModel>() {
   @Override 
   public Object render(BaseModel model, String property, 
                                   ColumnData config,
              int rowIndex, int colIndex,
              ListStore<BaseModel> store,
              Grid<BaseModel> grid) {

         Object value = model.get(property);         
         if (value != null)             
             return "<span " + 
                    "style='background-color:yellow;'>" + 
                    value.toString() + 
                    "</span>";
          return null;     
     }
});

The result of this code is like this, quite OK, but not perfect, the yellow background is set as long as the value is.


Another idea is to replace the span element with div, and the result will be like this


 we see the yellow background is spread more, but there is still lot of white space between cells.

And now,  the right solution is to use the "style" of the ColumnConfig object passed as parameter, like in this code:

ColumnConfig typeCol = new ColumnConfig("Type"); 

typeCol.setRenderer(new GridCellRenderer<BaseModel>() {    
    @Override
    public Object render(BaseModel model, String property, ColumnData config,
                         int rowIndex, int colIndex, ListStore<BaseModel> store,
                         Grid<BaseModel> grid) {
          config.style = "background-color:yellow;";
          Object value = model.get(property);
          return value;          
     } 
});

and the result is the expected one:
Cheers!

5 comments:

  1. In the same way, you can set the cell background image:

    config.style = "background-image: url(resources/images/cell.png);";

    Cheers!

    ReplyDelete
  2. I tried this method and it doesn't work with TreeGrid, only 2 rows are displayed. They are colored as desired but the rest of the rows disappear..
    Any suggestions

    ReplyDelete
  3. I'll try to help you :-) Can you post somewhere your code from the renderer, please?

    Cheers!

    ReplyDelete
  4. Thank you very much man, I was searching exactly this to set padding for a particular column

    ReplyDelete
  5. It was not so easy in my case.
    > I have a button in the cell of one table's column and I'd like to remove padding/margin. My button should hit the cell's border.

    my solution :

    ..
    config.id="editCell"
    ..

    cssFile
    ..
    .x-grid3-col-editCell {
    padding: 0;
    margin : 0;
    }
    ..

    ReplyDelete