我通常通过实现包装另一个 TableCellRenderer 的装饰器样式 TableCellRenderer 实现来解决这个问题。这样,您可以为每一列保留特定类型的渲染器,但将它们中的每一个包装在负责行突出显示的装饰器渲染器中。
这是我编写的一个示例,它使用这种方法将每个交替行的背景设置为浅灰色。
public class AlternateRowRenderer implements TableCellRenderer {
private final TableCellRenderer wrappedRenderer;
public AlternateRowRenderer(TableCellRenderer wrappedRenderer, Color highlightColour) {
this.wrappedRenderer = wrappedRenderer;
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component ret = wrappedRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
ret.setBackground(getTableBackgroundColour(table, value, isSelected, hasFocus, row, column));
return ret;
}
@SuppressWarnings({"UnusedDeclaration"})
public static Color getTableBackgroundColour(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Color ret;
if (row % 2 != 0) {
ret = isSelected ? ColourUtil.mergeColours(LIGHT_GREY, table.getSelectionBackground(), 0.75) : LIGHT_GREY;
} else {
ret = isSelected ? table.getSelectionBackground() : table.getBackground();
}
return ret;
}
}