0

I am trying to change the color of entire row due to a column's value.

the columns I test it's value is the third one in my table.

Here is my cell rendering class code :

public class CustomTableCellRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
            Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(
                table, obj, isSelected, hasFocus, row, column);

        String etat = (String) table.getModel().getValueAt(row, 2);
        switch (etat) {
            case "Annulé":
                cell.setBackground(Color.RED);
                break;
            case "Traitement":
                cell.setBackground(Color.yellow);
                break;
            case "Livré":
                cell.setBackground(Color.GREEN);
                break;
            default : 
                // Here I want to change the color to the default color
        }
        return cell;
    }
}

in my test I only included three cases, and I want in the default case my row to be colored by the default color which is provided by the look & feel.

How can I do that ?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Aimad Majdou
  • 563
  • 4
  • 13
  • 22

1 Answers1

2

I am trying to change the color of entire row due to a column's value.

  • look at prepareRenderer

  • DefaultTableCellRenderer in your form work for cell only, is required to apply renderer to whole row by using methods int row, int colum from TableCellRenderer

  • String etat = (String) table.getModel().getValueAt(row, 2);, use int modelRow = convertRowIndexToModel(row);, because JTables view can be sorted or filtered, then view index doesn't match to model index, (sorted or filtered)view index can living own life

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    +1, See [Table Row Rendering](http://tips4java.wordpress.com/2010/01/24/table-row-rendering/) for this and other examples when overriding the prepareRenderer() method. – camickr Jun 01 '13 at 15:09
  • To apply my rendering to the whole row I used for each column : `tcol = jTable1.getColumnModel().getColumn(0); tcol.setCellRenderer(new CustomTableCellRenderer());` – Aimad Majdou Jun 01 '13 at 17:22
  • And when I used `int modelRow = convertRowIndexToModel(row);` it shows me that : `error: cannot find symbol int modelRow = convertRowIndexToModel(row);` – Aimad Majdou Jun 01 '13 at 17:24
  • @user2417302 [prepareRenderer & convertRowIndexToModel](http://stackoverflow.com/a/6901508/714968) – mKorbel Jun 01 '13 at 17:51