我有一个名为sponsorIndexArr的整数数组,其中包含我想要更改表格颜色的单元格的索引(我也希望使该单元格不可选)。该表是一列,因此我只需要单元格的行索引。
以下是一些相关代码:
// 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)
时,每个细胞都变成青色。
当我选择任何其他单元格时,背景将覆盖文本。当我摆脱this.setEnabled(true)
然后我没有遇到这个问题,但随后每个单元格都被禁用(文本变灰)。
答案 0 :(得分:4)
发生的事情是只有最后一个SponsorIndexArr索引的单元格才会改变颜色。
你的渲染器概念是错误的。您的渲染器有一个循环,表示您正在尝试一次渲染所有单元格。这不是渲染器的工作方式
每个单元格都使用相同的渲染器。每次需要渲染单元格时,都会调用渲染器。因此,如果您有10行,则渲染器将被调用10次,渲染器的状态将更新10次以反映单元格的状态。
我有一个名为sponsorIndexArr的整数数组,其中包含我想要更改颜色的单元格的索引
我建议您使用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;
}