The color of only specific cells in JTable

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

enter image description here

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()); 
+5
source share
1 answer

Make sure that when your cell does not have to be yellow, set the background color to white (or the background color of the table).

A renderer that extends DefaultTableCellRenderer uses the same component (a JLabel ) as a template for all cells (cf DefaultTableCellRenderer implementation notes - they call it rubber stamping). After you set its background to yellow, it will remain yellow to render successive cells until you change its background color again.

Replace the for loop with the following:

 boolean isYellow = false; for (int i = 0; i < 3; i++) { if ((row == coordinatesYellow[i][0]) && (column == coordinatesYellow[i][1])) { c.setBackground(Color.yellow); isYellow = true; } } if( !isYellow ) c.setBackground(Color.white); 
+2
source

Source: https://habr.com/ru/post/1240344/


All Articles