JTable TableCellRenderer未正确着色

时间:2018-06-08 08:31:56

标签: java swing jtable tablecellrenderer

我使用自定义JTable创建了一个简单的DefaultTableCellRenderer。它本身工作正常(着色最后一栏)。但是,只要我选择一行或过滤/不过滤它,该行就会着色,即使它根本不应着色。

我的渲染器:

public class StatusCellRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int col) {
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                table.convertRowIndexToModel(row), col);
        DataTableModel model = (DataTableModel) table.getModel();
        String data = model.getValueAt(table.convertRowIndexToModel(row), col).toString();
        if (col == 3 && data.equalsIgnoreCase("successful") && !data.isEmpty()) {
            c.setBackground(Color.GREEN);
        }
        if (col == 3 && !data.equalsIgnoreCase("successful") && !data.isEmpty()) {
            c.setBackground(new Color(255, 51, 51));
        }
        return c;
    }
}

最初看起来如何(以及它应该如何看待):

enter image description here

选择2行(顶部和底部)后:

enter image description here

如您所见,有几行绿色,根本不应该着色。更令人不安的是,我只选择了绿色区块的顶部和底部一行,这意味着它会自动对两者之间的行进行着色。

如何停止此行为并仅对第一张图片中显示的行进行着色?

接受的答案帮助我克服了这些问题,这是最终的代码:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int col) {
    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
            table.convertRowIndexToModel(row), table.convertColumnIndexToModel(col));
    DataTableModel model = (DataTableModel) table.getModel();
    String data = model.getValueAt(table.convertRowIndexToModel(row), table.convertColumnIndexToModel(col))
            .toString();
    if (!isSelected) {
        if (col == 3 && data.equalsIgnoreCase("successful") && !data.isEmpty()) {
            c.setBackground(Color.GREEN);
        } else if (col == 3 && !data.equalsIgnoreCase("successful") && !data.isEmpty()) {
            c.setBackground(new Color(255, 51, 51));
        } else {
            c.setBackground(Color.WHITE);
        }
    } else {
        c.setBackground(c.getBackground());
    }
    return c;
}

如果选择了单元格,则颜色为蓝色,如果没有,则根据值将颜色设置为白色,绿色或红色

1 个答案:

答案 0 :(得分:2)

由于将重复使用渲染器组件,因此请考虑在没有条件匹配时设置默认颜色:

    if (col == 3 && data.equalsIgnoreCase("successful") && !data.isEmpty()) {
        c.setBackground(Color.GREEN);
    }
    else if (col == 3 && !data.equalsIgnoreCase("successful") && !data.isEmpty()) {
        c.setBackground(new Color(255, 51, 51));
    }
    else {
        c.setBackground(Color.GRAY.brighter());
    }