我使用此代码为不同颜色的ly jtable行着色:
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.WHITE : Color.LIGHT_GRAY);
return c;
}
});
它有效,现在我想将用户选择的行着色为与上述颜色不同的另一种颜色:
table.setSelectionBackground(Color.RED);
但它做了什么 我怎样才能做到这一点?
提前谢谢
答案 0 :(得分:5)
您的渲染器会覆盖DefaultTableCellRenderer
尝试类似......
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (!isSelected) {
c.setBackground(row % 2 == 0 ? Color.WHITE : Color.LIGHT_GRAY);
}
相反
答案 1 :(得分:0)
您可以根据需要使用getSelectedRow()
或getSelectedColumn()
。例如:
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
comp.setForeground(Color.BLACK); // Default colour of cell
if (this.getSelectedRow() == row || this.getSelectedColumn() == column) return comp;
else {
.... // Other formatting rules here
}
return comp;
}