Search code examples
swttableviewer

SWT - Table Row - Changing font color


Is it possible to change the font color for a row based on a value in one of the columns?

My table has a column that displays a status. The value of the column is going to either be Failed or Success.

If it is Success I would like for that rows font be green. If the status equals Failed, I want that rows font be red.

Is this possible, if so where would I put the logic.

EDIT

Here is my Table Viewer code, I am not going to show all the columns, just a couple

private void createColumns() {

  String[] titles = { "ItemId", "RevId", "PRL", "Dataset Name", "Printer/Profile" , "Success/Fail" };
  int[] bounds = { 100, 75, 75, 150, 200, 100 };

  TableViewerColumn col = createTableViewerColumn(titles[0], bounds[0], 0);
  col.setLabelProvider(new ColumnLabelProvider() {
     public String getText(Object element) {
        if(element instanceof AplotResultsDataModel.ResultsData) {
           return ((AplotResultsDataModel.ResultsData)element).getItemId();
        }          
        return super.getText(element); 
     }
  }); 

  col = createTableViewerColumn(titles[1], bounds[1], 1);
  col.setLabelProvider(new ColumnLabelProvider() {
     public String getText(Object element) {
        if(element instanceof AplotResultsDataModel.ResultsData) {
           return ((AplotResultsDataModel.ResultsData)element).getRevId();
        }          
        return super.getText(element); 
     }
  });    --ETC

Solution

  • Check element state and return the color that you want to use

    Viewer implementation        
        ColumnLabelProvider
            public Color getForeground(Object element)
    

    For Table use

    TableItem
             setForeground(Color color) 
             setForeground(int index, Color color)
    

    As you are using ColumnLabelProvider for each column, you need to override getForeground(Object element) for each column. Another way, do not add ColumnLabelProvider for each column.

    Set LabelProvider at TableViewer level.

    TableViewer.setLabelProvider(ColumnLabelProvider labelProvider). As you don't have label provider set at column level, tableviewer get its display text, image, font, background, foreground, etc. for each cell from the label provider set at TableViewer level.