I would like to set the color of a cell based on the value of the cell. Having googled around for a bit i found out that i can do it using something like this:
public class TableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col)
{
// get the DefaultCellRenderer to give you the basic component
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
// apply your rules
if (value.toString().equals("Red"))
c.setBackground(Color.RED);
else
c.setBackground(Color.GRAY);
return c;
}
}
The problem i have though is that the code i would like to modify is already setting the TableCellRendererer for the columns of the JTable. There is a function in the code that looks like this:
private void configureTableColumns() {
Enumeration columns = this.table.getColumnModel().getColumns();
while (columns.hasMoreElements()) {
TableColumn tableColumn = (TableColumn) columns.nextElement();
this.setCellRenderer(tableColumn);
TableCellRenderer renderer = tableColumn.getCellRenderer();
if (renderer == null) {
renderer = this.table.getDefaultRenderer(Object.class);
}
tableColumn.setCellRenderer(renderer);
this.setCellEditor(tableColumn);
}
}
With the above code, do i still need to add the TableCellRenderer class shown previously? All i want to do is to check if the value of the cell is 'ABC' and set the background to RED.
Update:
I did try adding my version of the TableCellRenderer as an inner class in the code i want to modify but i get an error that there is a type mismatch at tableColumn.getCellRenderer().
Type mismatch: cannot convert from TableCellRenderer to MyTableExample.TableCellRenderer
Thanks