Java - 更改 JTable 中某些单元格的颜色

Java - Change colors of some cells in JTable

我有一个名为 sponsorIndexArr 的整数数组,其中包含我想要在 table 中更改颜色的单元格的索引(我还想让该单元格无法 select ). table 是一列,所以我只需要单元格的行索引。

这里是一些相关的代码:

// Configure sponsor table
sponsorstableModel = new DefaultTableModel(sponsorsTableList, new String[]{"Sponsors"}
    @Override
    public boolean isCellEditable(int row, int column) {
       return false;
    }
};
sponsorsTable = new JTable(sponsorstableModel);
sponsorsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sponsorsTable.addMouseListener(this);

sponsorsTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            for (int entry : sponsorIndexArr) {
                System.out.println(entry + " " + row);
                if (entry == row) {
                    System.out.println("HERE");
                    this.setBackground(Color.CYAN);
                    this.setEnabled(false);
                } else {
                    setBackground(null);
                    this.setEnabled(true);
                }
            }
            return this;
        }
    });

程序正在正确的地方打印 "HERE"。然而,实际情况是只有最后一个索引为 sponsorIndexArr 的单元格在改变颜色。当我摆脱 setBackground(null) 时,每个单元格都变成青色。

另外,当我 select 任何其他单元格时,背景会覆盖文本。当我摆脱 this.setEnabled(true) 然后我没有这个问题,但随后每个单元格都被禁用(文本变灰)。

what is happening is that only the cell with the last index of sponsorIndexArr is changing colors.

你对渲染器的概念是错误的。您的渲染器有一个循环,表明您正在尝试一次渲染所有单元格。这不是渲染器的工作方式

每个单元格都使用相同的渲染器。每次需要渲染单元格时,都会调用渲染器。因此,如果您有 10 行,渲染器将被调用 10 次,渲染器的状态将更新 10 次以反映单元格的状态。

I have an array of ints called sponsorIndexArr which contains the indices of the cells that I want to change the color

我建议您改为使用 Set 整数。然后您的渲染器将进行简单检查以查看行索引是否在集合中,然后确定应如何渲染单元格。

代码可能类似于:

@Override
public Component getTableCellRendererComponent(
    JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    if (isSelected)
        setBackground( table.getSelectionBackground() );
    else if (yourSet.contains(row))
        setBackground( Color.CYAN );
    else
        setBackground( table.getBackground() );

    return this;
}