Question

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?

Was it helpful?

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.

OTHER TIPS

How to Use Tables: Using Custom Renderers mentions this alternative approach: "To specify that cells in a particular column should use a renderer, you use the TableColumn method setCellRenderer()."

Addendum: A benefit of this approach is that the renderer "sticks" to the column if the user drags it to a different position. In this example, replace setDefaultRenderer() with setCellRenderer().

table.getColumnModel().getColumn(DATE_COL).setCellRenderer(new DateRenderer());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top