我编写了一个默认表格,如下所示:
public class CustTableRenderer extends DefaultTableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
try {
Object cellObj = table.getModel().getValueAt(row, 7);
double cellValue = (Double) cellObj;
if (cellValue < 0) {
comp.setBackground(new Color(255, 48, 48));
} else if (cellValue == 0) {
comp.setBackground(new Color(173, 255, 47));
} else {
comp.setBackground(Color.white);
}
if (isSelected) {
comp.setBackground(new Color(71, 60, 139));
TableModel model = table.getModel();
}
} catch (Exception e) {
e.printStackTrace();
}
return comp;
}
}
要突出显示包含第7列减值的行,我还将setAutoCreateRowSorter
设置为true
。我的问题是,当我单击一个标题进行排序时,表格已排序,但突出显示的行未更改,因此突出显示错误的行。
如何在排序时重绘表格?
答案 0 :(得分:7)
传递到渲染器的坐标在视图坐标系中,您必须在访问模型之前将它们转换为模型坐标:
int modelRow = table.convertRowIndexToModel(row);
int modelColumn = table.convertColumnIndexToModel(column);
cellObject = table.getModel().getValueAt(modelRow, modelColumn);