0

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;
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Grim
  • 2,398
  • 4
  • 35
  • 54

2 Answers2

4

You renderer should check isSelected and condition the Component colors accordingly. In outline,

@Override
public Component getTableCellRendererComponent(
    JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int col) {
    …
    if (isSelected) {
        setForeground(getSelectionForeground());
        setBackground(getSelectionBackground());
    } else {
        setForeground(getForeground());
        setBackground(getBackground());
    }
    return this;
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • See also this [Q&A](http://stackoverflow.com/q/9607670/230513) discussing `DefaultTableCellRenderer`. – trashgod Aug 30 '15 at 22:38
  • Also, if the op is using DefaultTableCellRenderer, just call the super method, but since the op hasn't provided this information, this is the best solution – MadProgrammer Aug 30 '15 at 23:22
  • I am not using the DefaultTableCellRenderer but implementing TableCellRenderer – Grim Aug 30 '15 at 23:57
  • @MadProgrammer is correct; I cited the related Q&A as a guide to avoiding this [pitfall](http://stackoverflow.com/a/9617446/230513); see also this related currency [example](http://stackoverflow.com/a/10067560/230513). – trashgod Aug 31 '15 at 00:06
2

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.

camickr
  • 321,443
  • 19
  • 166
  • 288