繁体   English   中英

JTable TableCellRenderer无法正确着色

[英]JTable TableCellRenderer not coloring correctly

我使用自定义的DefaultTableCellRenderer创建了一个简单的JTable 就其本身而言,它可以正常工作(为最后一列着色)。 但是,一旦我选择了行或对其进行了过滤/取消过滤,即使该行根本没有被着色,该行也会被着色。

我的渲染器:

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

最初的外观(以及始终应如何显示):

在此处输入图片说明

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

在此处输入图片说明

如您所见,有几行是绿色的,根本不应该上色。 更令人不安的是,我只选择了绿色块的顶部和底部行,这意味着它还会自动为中间的行着色。

如何停止这种行为,只为第一行中的颜色着色?


接受的答案非常有助于我克服这些问题,这是最终代码:

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

如果选择了该单元格,则该单元格显示为蓝色;如果未选中该单元格,则根据该值将其显示为白色,绿色或红色。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM