我有一个 JTable 对象,它显示 Excel 表格的内容。加载另一个 Excel 表格后,必须显示差异(因此某些单元格将更改其背景颜色,例如蓝色)。这是我的表的结构。
这是我的代码:
tblGSM.setDefaultRenderer(Object.class, new CustomTableRenderer(diffs));
CustomTableRenderer.java
public class CustomTableRenderer extends DefaultTableCellRenderer {
private Vector<Diff> diffs;
public PersoTableRenderer(Vector<Diff> diffs){
this.diffs = diffs;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = null;
for (int x = 0; x < diffs.size(); x++){
Diff d = diffs.elementAt(x);
c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
d.getRow(), d.getColumn());
c.setBackground(Color.BLUE);
}
return c;
}}
Diff.java
/*
A class to store the difference of corresponding cells
*/
public class Diff {
private int row, col;
public Diff(int row, int col){
this.row = row;
this.col = col;
}
public Diff(){
this(0,0);
}
public int getRow(){
return row;
}
public int getColumn(){
return col;
}
}
我的问题是差异已正确填充,但应更改的单元格颜色却未正确填充。结果第 1、2、、3 和 7 列中的所有单元格都已更改。那么解决办法是什么呢?
最佳答案
来自the documentation for DefaultTableCellRenderer
(强调我的):
However JTable employs a unique mechanism for rendering its cells and therefore requires some slightly modified behavior from its cell renderer. The table class defines a single cell renderer and uses it as a as a rubber-stamp for rendering all cells in the table; it renders the first cell, changes the contents of that cell renderer, shifts the origin to the new location, re-draws it, and so on.
如您所见,super.getTableCellRendererComponent()
可能会为多个单元格返回相同的组件,因此您的方法将不起作用。
请注意getTableCellRendererComponent
每个单元格在渲染时被调用一次,因此除了上述警告之外,在检索单个单元格的组件不正确。
相反,您将仅修改所请求组件的背景颜色,例如(伪代码):
c = super.getTableCellRendererComponent(..., row, column)
// also don't forget to translate to model coords
model_row = table.convertRowIndexToModel(row)
model_column = table.convertColumnIndexToModel(column)
if diffs contains model_row,model_column:
c.setBackground(blue)
else
c.setBackground(table.getBackground()) // don't forget to reset
return c
请注意,如果它不是“差异”单元格,您还必须将背景颜色重置为其默认值,因为正如文档所述,组件在多个单元格之间共享。
顺便说一下,而不是存储 Vector<Diff>
在你的渲染器中,你确实应该使用正确的 TableModel
为此,然后查询模型以获取信息。通过一个合理实现的模型,这还可以让您恒定时间查找单元格是否应该为蓝色,而不必搜索 Diff
的整个列表。 s。
PS:Don't forget to translate your renderer/view coordinates to model coordinates当与您的 Diff
一起工作时s,假设它们位于模型坐标中。 View 坐标可能与模型坐标不一致,例如表已排序或用户已重新排列列。我已经在上面的伪代码中展示了这一点。
Here is a complete example显示表格模型和每个单元格自定义背景的使用。您可以对表格进行排序并重新排列其列。
关于java - 如何更改 JTable 多个不同位置的颜色单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42483175/