Reputation: 6689
I have little problem with sorting my JTable, I can't get the functionality I want. In my window I have something like total commander, in one column there are files and if there is any, parent folder in the other one there is or number of bytes. What I want is, if I click on File Name column I want the parent folder always on top, then ascending/descending folder names and then ascending/descending file names and if I click on File Type I want directories to remain untouched and then I want normal files in ascending/descending order by their size.
I tried to toy with RowSorters, my own comparators but as I said I can't get what I want, should I catch the event myself, then manually sort values and update my model (which I use btw.)? Is there some elegant way to do what I want?
Upvotes: 0
Views: 2029
Reputation: 9307
It sounds like you might want to use a tree table instead. Please take a look at: http://java.sun.com/products/jfc/tsc/articles/treetable1/
If you want to use JTable itself then you can try to implement sorting in table model as it might be easier.
TableRowSorter<TableModel> sorter =
new TableRowSorter<TableModel>(getModel()) {
Map<Integer, SortKey> keys = new HashMap<Integer, SortKey>();
public void toggleSortOrder(int column)
{
SortKey key = keys.get(column);
SortOrder order = null;
// Get last sort order.
if (key != null) {
if (key.getSortOrder() == SortOrder.DESCENDING){
order = SortOrder.ASCENDING;
}
else {
order = SortOrder.DESCENDING;
}
}
else {
order = SortOrder.DESCENDING;
}
keys.put(new SortKey(column, order));
getTableModel().sort(keys);
}
};
setRowSorter(sorter);
Upvotes: 2