Search code examples
javaswingjtabletablecellrenderer

JTable trouble changing colors for first column


i try to change the color of fields in a JTable according to their value. I don't want to change any color of the first column but it changes anyway in a buggy way(some fileds are not correctly filed like University and Possible_Reviewer):x is the first column

My code is as following:

table.setDefaultRenderer(Object.class, new CustomRenderer());

private class CustomRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int col){
         Component comp = super.getTableCellRendererComponent(table,  value, isSelected, hasFocus, row, col);
         try {
             Double val =  Double.parseDouble(value.toString());

             if(col == 0){
                 comp.setBackground(Color.white);
             } else {
                 comp.setBackground(changeColor(val));
             }
         } catch (NumberFormatException e){}
         return( comp );
    }

    private Color changeColor(Double val) {
        //returns a Color between red and green depending on val
    }
}

The weird thing is that when i use "col == 2" it turns the second column white but the first remains strangely colored.

Anyone an idea?


Solution

  • You should extend JTable class and override this method:

    public TableCellRenderer getCellRenderer(int row, int column){}
    

    Otherwise JTable will use the same renderer for each cell in the same column.

    EDIT:

    Like @Mark Bramnik pointed out, it's better to not instantiate a new TableCellRenderer object for every getCellRenderer call. You could implement a method like the following:

    setCellRenderer(int row, int col, TableCellRenderer render) 
    

    and store the renderer in the extended JTable itself.