I am trying to be able to color separate cells in a JTable, but I got only so far to apply a TableCellRenderer on a whole column, which then obviously malfunctions. I have a custom JTable:
public class JColorTable extends JTable{
(...)
public void setCellColor(int col, int row, Color newColor) {
getColumnModel().getColumn(col).setCellRenderer(new ColorField(col, row, newColor, background));
repaint();
}
}
ColorField looks like this:
class ColorField extends DefaultTableCellRenderer {
(...))
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (row == newRow && column == newCol) {
l.setBackground(Color.red);
} else {
l.setBackground(defaultColor);
}
return l;
}
}
This works like a charm when I have a single colored cell in a column, but when I try to color another cell in that column, the previous gets deleted (due to the condition in ColorField not applying for the previous column).
Is there a way to only apply ColorField to a single cell, rather than the whole column? If so, how? I did not find anything suitable, I'm afraid.