Java – How to change color of row in JTable


I want to change color of whole row in my JTable.

I defined the JTable:

JTable table = new JTable(data, columnNames);

where data, columnNames are the String tables.

The most common way to do this is to write own class:

public class StatusColumnCellRenderer extends DefaultTableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {

            //Cells are by default rendered as a JLabel.
            JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

            //Get the status for the current row.


            //Return the JLabel which renders the cell.
            return l;

and call:

this.table.getColumnModel().getColumn(0).setCellRenderer(new StatusColumnCellRenderer());

But it is doesn't work. What am I doing wrong?

Best Solution

You're setting the TableCellRenderer correctly initially but then you're replacing it with this code:

for (int i = 0 ; i < table.getColumnCount(); i++)
   table.getColumnModel().getColumn(i).setCellRenderer( centerRenderer );

Change it so that it sets the colored cell renderer at the correct index (and add braces(!)):

for (int i = 0; i < table.getColumnCount(); i++) {
    TableColumn column = table.getColumnModel().getColumn(i);
    if (i == COLOR_COLUMN) { // COLOR_COLUMN = 1
        column.setCellRenderer(new StatusColumnCellRenderer());
    } else {