tags:

views:

739

answers:

1

I have an implementation of a DefaultTableCellRenderer. When someone selects a row in the table, the row gets highlighted green. If I wanted to highlight the row under the one selected what is the easiest way to achieve this? Is this even possible without having to re-render the entire table?

So at the moment, I have something that looks like this:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (isSelected) {
        component.setBackground(Color.GREEN);

        // Somewhere here I would like to retrieve the row below the current row and give it another color

    } else {
        component.setBackground(Color.WHITE);
    }
    return component;
}
+3  A: 

Turn your thinking around a bit. You don't need the selected row's renderer to control the row below. What you should do have each row check and see if the row above is selected, and if it is it then it highlights itself.

if (table.isRowSelected(row - 1)) {
    // Highlight self.
    component.setBackground(Color.YELLOW);
}

You may also need to cause the highlighted row to get repainted whenever the selection changes. I suspect Java will only repaint the rows that have been selected/deselected by default, so the row below won't get repainted. I don't have the JDK on my current machine so I can't test, but if that is the case then something like this should do the trick:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent event) {
        table.repaint();
    }
});

Actually you could be smarter and only repaint the exact row(s) that needs to be repainted. I will leave that as an exercise (a difficult and not terribly worthwhile exercise) if you are so inclined.

John Kugelman