0

I am wondering if I can set the specified row and column color without defining my own custom TableCellRender.

Currently I am using this code

TableCellRenderer cellRenderer = this.devicePropertyTable.getCellRenderer(1, 1);
Component cellRenderComponent = cellRenderer.getTableCellRendererComponent(this.devicePropertyTable, "", false, false, 1, 1);

if (propertyValue.equalsIgnoreCase("true"))
{
    cellRenderComponent.setBackground(Color.green);
}
else
{
    cellRenderComponent.setBackground(Color.red);
}

I would assume that this would get the cell render-er for the table node 1,1 and color it with the respective color. But what happens is it will color the whole table.

Is there another way to do this without creating a custom TableCellRender?

Chris Watts
  • 2,284
  • 4
  • 23
  • 28
  • 1
    custom renderer's are _the_ small coin designed for ... well .. customizing visuals in the collection components :-) If you need a stronger and more pluggable support than core Swingx, you might want to take a look into SwingX – kleopatra Jul 28 '11 at 11:26

2 Answers2

4

I am wondering if I can set the specified row and column color without defining my own custom TableCellRender.

Override the prepareRenderer(...) method of JTable.

See Table Row Rendering for some examples to get you started.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

EDIT: For this use case better use prepareRenderer as mentioned in the answer above.

You will have to extend JTable and override

<!-- language: lang-java -->
getCellRenderer(int row, int column)

public class MyTable extends JTable
{
   @Override
   public TableCellRenderer getCellRenderer(int row, int column) 
   {
      return new TableCellRenderer()
      {
          Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, 
                    int row, int column)
          {
              Component cellRenderComponent = this.MyTable.super.getCellRenderer(row, column);
              if (getModel().getValue(row,column).toString().equalsIgnoreCase("true"))
              {
                  cellRenderComponent.setBackground(Color.green);
              }
              else
              {
                  cellRenderComponent.setBackground(Color.red);
              }

          }
      }
   }

}
DoubleMalt
  • 1,263
  • 12
  • 17
  • 1
    -1 because it's simply wrong (you sure do not want to short-circuit table's look-up for an appropriate renderer) – kleopatra Jul 28 '11 at 11:24