Federico Giorgi
Federico Giorgi

Reputation: 10735

Exclude column from sorting in JTable

I have a simple Swing JTable and a TableRowSorter made by me. However, I would exclude the first column from the sorting, as I want to keep it to show row numbers. I can't see to find anything, except

sorter.setSortable(0, false);

Which makes the column not clickable, but still sortable when another column is clicked... So quick question will be: how to keep a column from being sorter by a TableRowSorter?

Thank you!

Upvotes: 3

Views: 4723

Answers (3)

camickr
camickr

Reputation: 324108

If the row number isn't part of the data, then it should not be stored in the model.

Instead I would use a row header that displays a row number. Something like you would see in Excel. You can use the Row Number Table for this.

Upvotes: 0

Devon_C_Miller
Devon_C_Miller

Reputation: 16518

So, with a JTable (ex below) sorting on column A would produce the following. However, you want the data to sort, but not the row numbers, correct?

|row| column A  |       |row| column A  |
+---+-----------+       +---+-----------+
| 1 | blah blah |  -->  | 1 | blah blah |
| 2 | something |       | 3 | more blah |
| 3 | more blah |       | 2 | something |

I would approach this with a TableCellRenderer for column 0. The trick is to ignore the value passed and instead use the row parameter.

public class RowRenderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object color,
        boolean isSelected, boolean hasFocus, int row, int column) {
        setText(Integer.toString(row));
        return this;
    }
}

Note: if you are paginating your table (ie the model does not contain all of the rows; for example only rows 100-200) you will need to advise the cell renderer of the amount to add to row to obtain the row number to display.

Upvotes: 5

Kevin K
Kevin K

Reputation: 9584

A JTable is designed around displaying rows of data, not cells of data, so it isn't really possible to prevent an individual column from sorting, as you put it. Instead I would try modifying your TableModel to return the row index for the value for that column:

@Override public Object getValueAt(int rowIndex, int columnIndex) {
    if (columnIndex == 0) return rowIndex;
    else {
        // handle other columns
    }
}

If that doesn't work you could also try modifying the table cell renderer to use the table row index instead.

Upvotes: 1

Related Questions