MikkoP
MikkoP

Reputation: 5092

Change only one cell's color in JTable

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;
        }
    }
);

Upvotes: 3

Views: 7872

Answers (1)

Steve Kuo
Steve Kuo

Reputation: 63134

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;
}

Upvotes: 3

Related Questions