tags:

views:

112

answers:

3

I want to color a Table row depending on whether there is a non-null in its 3rd column. Heres the code that I wrote : (ignore the braces)

public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {

        JComponent c =(JComponent) super.prepareRenderer(renderer, row, column);
        c.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
        if (column == 2 ){

                String value = (String) getValueAt(row, column);
                System.out.println(value);

                if (! value.equals(null)){

                    c.setForeground(Color.RED);
                }
            } 

The problem is when I execute this all the rows of the table get colored even if only 1 row has a non-null value in the 3rd column. Where am I going wrong?

+2  A: 

JTable's default renderer is a single instance for the entire table shared across multiple cells. Once you're setting the foreground, it will be set for all usages of it. You should set it back to the default color when the value is not null. Also, why are you using .equals(null) instead of == null?

Jeff Storey
Thanks this helped. as for the .equals, my java is still a bit shaky.
Goutham
+2  A: 

For efficiency reasons, the component returned by super.prepareRenderer() is used by multiple cells in the table. So, you need to handle the else pathway. I would try the following:

if (column == 2 ){
  String value = (String) getValueAt(row, column);
  System.out.println(value);

  if (value == null){
    // I suppose this one may not be needed since the value is null 
    // and nothing should appear in the table.
    c.setForeground(Color.Black);
  } else {
    c.setForeground(Color.RED);
  }
} else {
  // This is definitely needed
  c.setForeground(Color.Black);
}
Jay Askren
A: 

I hope that value is never null because then

value.equals(null)

would throw a NullPointerException!

Duppidupp