Search code examples
javaswingjtabletablecellrenderertablecelleditor

Change the color of some rows but not all in a JTable


I have created a custom cell renderer class to achieve this.

public class MatchTableCellRenderer extends DefaultTableCellRenderer{


    public Component getTableCellRendererComponent (JTable table,
                                                    Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell;
        cell = super.getTableCellRendererComponent(
                table, obj, isSelected, hasFocus, row, column);
        if( ((String[]) ((MatchTableModel) table.getModel()).getRow(row)).length==7 ){
            System.out.println(((String[]) ((MatchTableModel) table.getModel()).getRow(row))[0]+" "+((String[]) ((MatchTableModel) table.getModel()).getRow(row))[6]);

            cell.setForeground(Color.green);

        }
        return cell;
    }


}

And I have set this renderer to be used by my table's columns:

    tempColumn = table.getColumnModel().getColumn(0);
    tempColumn.setCellEditor(new MacColumnEditor());
    tempColumn.setCellRenderer(new MatchTableCellRenderer());

    tempColumn = table.getColumnModel().getColumn(1);
    tempColumn.setCellEditor(new IpColumnEditor());
    tempColumn.setCellRenderer(new MatchTableCellRenderer());

    tempColumn = table.getColumnModel().getColumn(2);
    DefaultCellEditor dfEditor=new DefaultCellEditor(new JTextField());
    dfEditor.setClickCountToStart(2);
    tempColumn.setCellEditor(dfEditor);
    tempColumn.setCellRenderer(new MatchTableCellRenderer());

I want the rows which contain a String[] of length=7 green and the others with the default color. But it is interesting that all my rows become green. I have a print line as you can see. It is printed 4 times (my table has 12 rows), but all rows are made green, instead of 4. What am I doing wrong?


Solution

  • The reason is the infamous color memory (TM) of the DefaultTableCellEditor: you have to set the colors always, instead of only in one branch.

    if (myCondition) {
       setBackground(...) {
    } else {
       setBackground(...) 
    } 
    

    the exact details are explained in a recent thread