javaswingjxtable

Coloring some rows in JXTable


I have a problem with coloring some rows after resorting columns. I want to coloring every row which the 4th column equals to zero. So that I have overridden prepareRenderer() method like this:

public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    Component comp = super.prepareRenderer(renderer, row, column);
    int modelRow = convertRowIndexToModel(row);
    int modelColumn = convertColumnIndexToModel(column);
    double d = (double) getModel().getValueAt(row, 4);
    if(d <= 1e-4){
        comp.setForeground(Color.RED);
    }else{
        comp.setForeground(Color.BLACK);
    }
    return comp;
}

it works fine. (1st, 2nd and 15th rows colored to red) enter image description here

But after sorting some columns this row indices doesnt change.(1st, 2nd and 15th rows red again) enter image description here How to fix it ?


Solution

  • double d = (double) getModel().getValueAt(row, 4);
    

    The data in the model is never sorted so you need to use:

    double d = (double) getModel().getValueAt(modelRow, 4);