一种方法是存储模型中每行的当前颜色。下面是一个固定在 3 列和 3 行的简单模型:
static class MyTableModel extends DefaultTableModel {
List<Color> rowColours = Arrays.asList(
Color.RED,
Color.GREEN,
Color.CYAN
);
public void setRowColour(int row, Color c) {
rowColours.set(row, c);
fireTableRowsUpdated(row, row);
}
public Color getRowColour(int row) {
return rowColours.get(row);
}
@Override
public int getRowCount() {
return 3;
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public Object getValueAt(int row, int column) {
return String.format("%d %d", row, column);
}
}
请注意,调用 ;这将导致仅更新表的那一行。setRowColour
fireTableRowsUpdated
渲染器可以从表中获取模型:
static class MyTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
MyTableModel model = (MyTableModel) table.getModel();
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(model.getRowColour(row));
return c;
}
}
更改行的颜色非常简单:
model.setRowColour(1, Color.YELLOW);