Highlight cell when row is selected

风格不统一 提交于 2019-12-12 00:15:06

问题


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;
}

回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/32301649/highlight-cell-when-row-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!