1

Here is a code part of my project. I am try to change the color of desingated cells. But when i try it, all cells' color changing. Why is that ? Thanks.

private class cellRenderer extends DefaultTableCellRenderer {

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

        Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      if(row==column){
          cell.setBackground(Color.yellow);
      }     
        return cell;
    }
}
Ozan Ertürk
  • 465
  • 5
  • 17
  • 1
    possible duplicate of http://stackoverflow.com/questions/17732005/trying-to-color-specific-cell-in-jtable-gettablecellrenderercomponent-overide – ma cılay Mar 02 '16 at 19:05

1 Answers1

1

I think you need to restore the original color.

private class cellRenderer extends DefaultTableCellRenderer {
    Color originalColor = null;

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

      Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);


       if (originalColor == null) {
           originalColor = cell.getBackground();
      }

      if(row==column){
          cell.setBackground(Color.yellow);
      } else {
          cell.setBackground(originalColor);
      }

      return cell;
    }
}
bradimus
  • 2,472
  • 1
  • 16
  • 23
  • Best to take `isSelected` into account as well, ie don't set any background is it is `true`. Most often the standard background color, is `table.getBackground()`. – TT. Mar 02 '16 at 21:04