[英]Java - Change colors of some cells in JTable
我有一个称为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)
我没有这个问题,但是每个单元格都被禁用(文本变为灰色)。
发生的情况是,只有带有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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.