Krishna
Krishna

Reputation: 659

How to change jtable cell Background Dynamically

I am having a JTable table1 with 5 rows and 5 columns, and I would like to change the background color of 3rd column/cell of 2nd row, when I call a function like

changeBgColor(row,col);

Is this possible?

Upvotes: 2

Views: 4174

Answers (1)

Amarnath
Amarnath

Reputation: 8865

Override prepareRenderer method for doing that.

Example:

public Component prepareRenderer (TableCellRenderer renderer, int rowIndex, int columnIndex){  
    Component componenet = super.prepareRenderer(renderer, rowIndex, columnIndex);  

    if(rowIndex % 2 == 0) {  
       componenet.setBackground(Color.RED);  
    } else {
       componenet.setBackground(Color.GREEN);
    }
    return componenet;
} 

Here I am coloring all the rows at even positions as RED and all the rows at odd positions as GREEN.

As far as your problem is considered. Use the same approach just use a constraint stating,

if(rowIndex == 2 && columnIndex == 3) {
   componenet.setBackground(Color.RED);
}

Other than the above stated cell all the cells will get the default color.

Upvotes: 5

Related Questions