How to change jtable cell Background Dynamically

别来无恙 提交于 2021-02-10 19:52:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14342396/how-to-change-jtable-cell-background-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!