-1

I have a JTable in a frame which is frequently updated by different threads. I am looking for way to change background color of a cell of the JTable irrespective of its content, something like

    JTable.setColorAt(Color.YELLOW, 0, 0)

Is there anything like this exist? If not, is there a way to write something like this for beginner like me?

Please help.............

mre
  • 43,520
  • 33
  • 120
  • 170
gnmanoj
  • 1
  • 1
  • 1
  • @Audrius: It's similar but not a duplicate. The link requires to change the background of an edited cell, not to all cells. – Igor Rodriguez Mar 02 '13 at 17:34
  • no issue see answer by @Ravindra Gullapalli, there is constructor Object value, boolean isSelected, boolean hasFocus, int row, int column, each of parameters is about your question especially int row, int column, then only test if `conditions == int row` && `conditions == int column` then `setBackground(Color.YELLOW)` – mKorbel Mar 02 '13 at 18:47

1 Answers1

4

Define your own cell renderer class which sets background colour for the cell like this

public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
    public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        cellComponent.setBackground(java.awt.Color.YELLOW);
        return cellComponent;
    }
}

and attach it to your table

MyCellRenderer mcr = new MyCellRenderer();
for (int columnIndex = 0; columnIndex < myTable.getColumnCount(); columnIndex ++) {
            myTable.getColumnModel().getColumn(columnIndex).setCellRenderer(mcr);
        }
Ravindra Gullapalli
  • 9,049
  • 3
  • 48
  • 70
  • Appreciate your help Sorry for a lengthy delay from my side, I got stuck in something for two weeks……. . I tried this by adding condition, but the cell color is changing only when it is selected. Any suggestion ? – gnmanoj Mar 20 '13 at 14:46
  • Your question as marked as duplicate and a link to other question is also specified. Have a look at that too. In that `prepareEditor` is discussed. – Ravindra Gullapalli Mar 20 '13 at 14:52