简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM