javaswingjtablecellrenderer

Highlight cell when row is selected


The problem I am having is that when I select a row, the cell with a custom cell renderer doesn't highlight that cell but does the other cells.

public Component getTableCellRendererComponent(
    JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column)
{
    setFont(ApplicationStyles.TABLE_FONT);

    if (value != null)
    {
        BigDecimal decimalValue = toBigDecimal(value);
        decimalValue =
            decimalValue.setScale(2, BigDecimal.ROUND_HALF_EVEN);

        DecimalFormat formatter = new DecimalFormat("$##,##0.00");
        formatter.setMinimumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);
        String formattedValue = formatter.format(value);
        setText(formattedValue);
    }
    return this;
}

Solution

  • The easiest way to format data is to override the setValue(...) method of the default renderer as demonstrated in the Swing tutorial on Using Custom Renderers. Then you don't have to worry about the highlighting.

    Or maybe easier is to use the Table Format Renderer then all you need to provide is the Format to be used by the renderer.