Search code examples
javaswingjtabletablecellrenderer

Use custom JTableCellRenderes


I have a JTable with 6 columns. When adding a row to the table I need to add black color for the last cell in fist row. red color for second row. The corresponding color comes from a different method. This is my custom table cell renderer.

class CustomRenderer extends DefaultTableCellRenderer
{
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column, Color color)
    {
        JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        label.setBackground(color);
        return label;
    }
}

This is how I used it when adding a table row.

  private void addTableRow(String type, String name, String rank, String notes, String location, Color color)
    {
        boolean isExport = isExportEnable();
        tableModel.addRow(new Object[]
        {
            type,
            name,
            rank,
            notes,
            location,
            isExport
        }
        );
        for (int i = 0; i < tableModel.getRowCount(); ++i)
        {
            JTable.getColumnModel().getColumn(6).setCellRenderer((TableCellRenderer) new CustomRenderer().getTableCellRendererComponent(null, null, false, false, i, 6, color));
        }
    }

When I add the fist row it gets the correct color. But when I add the second row both first and second color cell fills with the second color. How can I get the exact row. Actually what I want is to fill the last cell of each row with a different color while adding a row.


Solution

  • You need to go have a look at Concepts: Editors and Renderers and Using Custom Renderers because you clearly don't understand how renderers work in Swing.

    You NEVER add a component to a JTable's TableModel, that's not it's responsibility.

    You configure the JTable's TableColumns to use specific renders, something like...

    table.getColumnModel().getColumn(6).setCellRenderer(new CustomRenderer);
    

    assuming you want a specific renderer for a specific column and not have it configured for a type of object