3

我使用此代码通过不同的颜色为 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);

但它有什么作用我怎么能做到这一点?

先感谢您

4

2 回答 2

5

您的渲染器正在覆盖由DefaultTableCellRenderer

尝试类似...

Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (!isSelected) {
    c.setBackground(row % 2 == 0 ? Color.WHITE : Color.LIGHT_GRAY);
}

反而

于 2013-01-22T00:00:46.600 回答
0

您可以使用getSelectedRow()or 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;
}
于 2017-06-01T14:13:47.640 回答