I'm looking for a solution for this problem: I have an excel file, that contains data. Some of the cells have yellow background. I already created a code for importing the text to JTable, which works fine. But I want to import the background-cell-color to specific cells also. For simplicity-sake of this example, I didn't use loops, reading the excel data from source etc. After reading the forum I understood I need CustomCellRenderer.
I have a problem with this approach, because this code colors the cells in the column correctly at first, but when I start to scroll over the colored cells in this table, it recolors the whole column to yellow. (see the screenshot)
I thought I could add else statement to specifically color the remaining cells to white, but this approach won't work for me, because I would be overwriting my previous cell results.
Can you point me to a solution on this one? (is this a bug, or expected behavior of JTable?). I'm using NetBeans and the GUI drag n drop generator
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class MyRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
int[][] coordinatesYellow = new int[3][2];
//[row][column] these cells are yellow
coordinatesYellow[0][0] = 3;
coordinatesYellow[0][1] = 2;
coordinatesYellow[1][0] = 4;
coordinatesYellow[1][1] = 2;
coordinatesYellow[2][0] = 2;
coordinatesYellow[2][1] = 2;
for (int i = 0; i < 3; i++) {
if ((row == coordinatesYellow[i][0]) && (column == coordinatesYellow[i][1])) {
c.setBackground(Color.yellow);
}
}
return c;
}
}
// And this is the statement I use for calling the renderer:
// resultsTable.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());