I have created a custom cell renderer to fill a cell by a particular color.
public class ColorInCellRenderer extends DefaultTableCellRenderer
{
private final Map<Point, Color> cellColors = new HashMap<Point, Color>();
public void setCellColor(int row, int column, Color color)
{
if (color == null)
{
cellColors.remove(new Point(row, column));
}
else
{
cellColors.put(new Point(row, column), color);
}
}
private Color getCellColor(int row, int column)
{
Color color = cellColors.get(new Point(row, column));
return color;
}
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);
Color color = getCellColor(row, column);
c.setBackground(color);
return c;
}
}
i used it in adding a row into jTable as follows.
private void addTableRow(String type, String name, String rank, String notes, String location, Color color)
{
tableModel.addRow(new Object[]
{
type,
name,
rank,
notes,
location
});
colorInCellRenderer.setCellColor(tableModel.getRowCount() - 1, INDEX_OF_THE_COLOR_COLUMN, color);
JTable.repaint();
}
It works properly and fill the cell correctly. But when I remove the row it does not remove the filled color cell. Instead of it the color column replaces with the color cell in the next row. I tried by repainting the jTable after removing a row. But it does not work.