我有一个名为sponsorIndexArr的inint数组,它包含我想要更改表格颜色的单元格索引(我也希望使该单元格不可选)。该表是一列,所以我只需要单元格的行索引。Java - 更改JTable中某些单元格的颜色
下面是一些相关的代码:
// 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
参见[*臭名昭著的彩色记忆™*](http://stackoverflow.com/a/9617446/230513)。 –