我有一个客户端/服务器应用程序,并且我的JTables是分页的,它仅显示一系列数据。现在,我想处理排序但服务器端。如何自定义默认排序实现?
最佳答案
我找到了一个可行的解决方案,但我确定这不是最好的解决方案! :)
...
final MyTableModel myModel = new MyTableModel();
final MySorter mySorter = new MySorter(myModel);
mySorter.addRowSorterListener(new RowSorterListener() {
@Override
public void sorterChanged(RowSorterEvent e) {
// server side sorting
sortDataByColumn(mySorter.getColumnToSort());
}
});
JTable table = new JTable();
table.setModel(myModel);
table.setRowSorter(mySorter);
...
class MySorter extends TableRowSorter<TableModel> {
private String columnToSort;
public MySorter(AbstractTableModel model) {
super(model);
}
@Override
public void sort() {
// do nothing! because server side sorting
}
@Override
protected void fireSortOrderChanged() {
// build a string like [+-]column_identifier.
// where + is for ASC and - for DESC ordering
final SortKey k = getSortKeys().get(0);
final String colName = getModel().getTableColumnModel()
.getColumn(k.getColumn()).getIdentifier().toString();
if (colName != null && !colName.isEmpty()) {
columnToSort = (k.getSortOrder() == SortOrder.ASCENDING ? '+' : '-') + colName;
} else {
columnToSort = null;
}
super.fireSortOrderChanged();
}
public String getColumnToSort() {
return columnToSort;
}
}