Change row color in Swing JTable after sorting rows

4.1k views Asked by At

We are using a JTable which displays data along with Status (New, Processed, Closed). Each status row has a different color which is achieved by overloading prepareRenderer() of JTable.

Now we need to sort that table and we are using table.setAutoCreateRowSorter(true); to achieve that. The rows get sorted properly, but the color of rows remains the same. We need to reapply the color to all the rows after this operation based on the status column.

I was wondering what could be the best way to achieve that. There are several ways I can think of:

  1. Repaint/Revalidate the table. But simply doing this would not work I think.
  2. Capture mouseClicked event and identify whether column header was clicked then call prepareRenderer() manually and then call repaint/revalidate
  3. Then I read one of the questions here wherein one of the answers was mentioned not to call repaint/revalidate directly, rather change the underlying data model and it will automatically call the above methods.

I don't know how to go about it. Can anyone please provide an insight into what is the correct way to achieve this?

1

There are 1 answers

0
Alexander On

For change cell color in JTable with setAutoCreateRowSorter(true) I used method table.getRowSorter().convertRowIndexToModel(row) in my TableCellRenderer

import javax.swing.*;

import javax.swing.table.DefaultTableCellRenderer;

import javax.swing.table.TableModel;

import java.awt.*;

public class OwnTableCellRenderer extends DefaultTableCellRenderer {

    public OwnTableCellRenderer() {
        super();
        setOpaque(true);
    }

    public Component getTableCellRendererComponent(JTable table, 
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus, 
                                                   int row, 
                                                   int column) {

        setBackground(Color.white);
        setForeground(Color.black);

        TableModel model = table.getModel();
        int modelRow = table.getRowSorter().convertRowIndexToModel(row);
        int columnStatusPosition = 5;
        String statusColumnValue = (String) model.getValueAt(modelRow, columnStatusPosition);

        if (statusColumnValue.equals("ACTIVE")) {
            if (isSelected) {
                setBackground(Color.green);
            } else {
                setBackground(Color.yellow);
            }
        }

        setText(value != null ? value.toString() : "");
        return this;
    }
}

And then

table.setDefaultRenderer(Object.class, new OwnTableCellRenderer());