问题
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