I’ve been following tutorials, learning this whole thing about JTable Renderers/Editors, but I got stuck trying to make a conditional renderer meant to display cells in different colors according to a set of conditions.
Here’s the SSCCE I put together:
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumnModel;
public class Demo2 extends javax.swing.JFrame {
public Demo2() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 300);
this.getContentPane().setLayout(new java.awt.GridLayout(1, 1));
Object[] colunas = {"Col 0"};
Object[][] dados = {{"A"},{"B"},{"C"},{"D"}};
JTable tbl = new JTable(dados,colunas);
TableColumnModel tcm = tbl.getColumnModel();
tcm.getColumn(0).setCellRenderer(new CustomCellRenderer());
JScrollPane sp = new JScrollPane(tbl);
this.add(sp);
}
class CustomCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(jtable, value, isSelected, hasFocus, row, column);
if (value.toString().equals("B")) {
c.setForeground(Color.GREEN);
c.setFont(c.getFont().deriveFont(Font.BOLD));
} else if (value.toString().equals("D")) {
c.setForeground(Color.BLUE);
c.setFont(c.getFont().deriveFont(Font.BOLD));
}
return this;
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Demo2().setVisible(true);
}
});
}
}
As I’d expect, the second cell has green foreground and is bold, and the 4th, blue and bold as well. However, the other cells seem to have been affected by the foreground color change as well.

Debugging with breakpoints, I see it executing setForeground in only the correct rows, though it executes both twice, which was unexpected.
Furthermore, if I change the last cell from “D” to “DD”, then every cell’s foreground turns green.
I think I’m missing something fundamental about renderers.
Where do you “un-bold” your font when it does not need to be bolded or change the colors back to the default? Remember that this isn’t done automatically, but that your code needs to specifically do this. I think that you need to have more else blocks to be able to respond to all cases.
i.e.,
JTable cells are not like individual components but rather rendered images of a component. Consider them as being made with a cookie cutter. If you change the cutter for one cell and don’t change it back, all subsequent cells will be effected.