'Java TableCellRenderer background color sets to a non default color and renders all cells in the table to the same color
I have a JXTable that I have Overridden the prepareRenderer method. I'm dynamically processing records on the table which is updated approximately every second. I'm changing the "Name" column cells to a different color in the prepareRenderer method. Typically it works fine though occasionally the entire table will change to the color of the first row's "Name" column. Once it happens, the table will continue to render every cell the same color. I added a debugger and found that the renderer's background color in the prepareRenderer is set to the "Name" color rather than the typical color of RGB 27,27,27 for a non selected cell.
One issue may be that I centered aligned all cells by setting each columns cell renderer as follows:
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
table.getColumnExt(Columns.DESCRIPTION.toString()).setPreferredWidth(150);
table.getColumnExt(Columns.DESCRIPTION.toString()).setCellRenderer(centerRenderer);
I'm not sure if setting a default renderer for each column as well as overriding the prepareRenderer method is causing issues, I could set the background color for every cell to RGB 27,27,27 in the prepareRenderer method when I detect it has changed though I still what like to understand how I may be inadvertently affecting the renderer's default background value.
private class CustomTable extends JXTable
{
private static final long serialVersionUID = 1L;
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component component;
component= super.prepareRenderer(renderer, row, column);
if (this.getColumnName(column).equals(DashboardTableModel.Columns.NAME.toString()))
{
if (record != null)
{
final Color color = record.getColor();
component.setForeground(Utils.getVisibleTextColor(color));
component.setBackground(color);
}
}
if(!component.getBackground().equals(this.getBackground())){
//occasionally the renderer background color gets set to the name column color
//and turns every cell to the same background color
//debug check renderer: renderer background color is set to the "Name" column
//rather than (RGB 27,27,27)
}
return component;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
