I am looking for a solution to this problem: I have an excel file containing data. Some of the cells have a yellow background. I already created code to import text into JTable, which works great. But I also want to import the background cell color into specific cells. For simplicity of this example, I did not use loops reading excel data from source, etc. After reading the forum, I realized that I needed a CustomCellRenderer.
I have a problem with this approach because this code first correctly colors the cells in the column, but when I start scrolling the colored cells in this table, it repaints the entire column to yellow. (see screenshot)
I thought I could add an else statement to specifically color the remaining cells in white, but this approach would not work for me, because I would rewrite my previous cell results.
Can you point me to this solution? (is this a bug or expected JTable behavior?). I use NetBeans and drag and drop GUI generator drag n

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());
source share