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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With