3

I know I can set the whole column's background color with this code, but how can I set a different color for each cell? I have a table with two columns and one to one thousand rows.

words.getColumn("columnNameHere").setCellRenderer(
    new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setText(value.toString());
            setBackground(Color.RED);
            return this;
        }
    }
);
MikkoP
  • 4,864
  • 16
  • 58
  • 106
  • Also consider overriding `prepareRenderer()`, compared to `TableCellRenderer` [here](http://stackoverflow.com/a/5799016/230513). – trashgod Aug 19 '12 at 15:27

1 Answers1

3

The row and column number are passed into getTableCellRendererComponent. So you could do something like:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    setText(value.toString());
    if (row==12 && column==2) {
        setBackground(Color.RED);
    }
    return this;
}
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257