Color selected row in jtable with a different color

I am using this code to color the ly jtable rows with different colors:

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;
        }
    });

      

it works, now I want to color the row selected by the user with a different color than the ones above:

table.setSelectionBackground(Color.RED);

      

but it does nothing How can I achieve this?

early

+3


source to share


2 answers


Your renderer overrides the color change applied DefaultTableCellRenderer

Try something like ...



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

      

Instead

+5


source


You can use getSelectedRow()

or getSelectedColumn()

, depending on your needs. For example:



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;
}

      

0


source







All Articles