views:

193

answers:

1

I have implemented a JTable named scrTbl in a program, and I wish to be able to vary text color in one column of this table, based on an external boolean variable called "up". My code related to this effort is as follows.

TableColumn tcol = scrTbl.getColumnModel().getColumn(9);
tcol.setCellRenderer(new CustomTableCellRenderer());

public class CustomTableCellRenderer extends DefaultTableCellRenderer
{
    @Override
    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);

        if (up && (row == nmbrStocks))
        {
            cell.setForeground(Color.green);
        }
        if ((!up) && (row == nmbrStocks))
        {
            cell.setForeground(Color.red);
        }
        return cell;
    }//Component
} //class getTableCell...

The point is to set the text color for column 9 and a particular row (indexed nmbrStocks) to green or red, based on the value of up.

But when it runs, it sets all of the text green. Is the renderer called each time a cell in column 9 is written to, or what is the protocol?

Thanks in advance for any help.

A: 

Since you only want to modify one column, adjust your code to specify the column as well as the row

    if (row == nmbrStocks && column == the_desired_column_you_wish_to_change)
    {
      if (up){
        cell.setForeground(Color.green);
      }else{
        cell.setForeground(Color.red);
      }
    }
brian_d