1

我有一个客户端/服务器应用程序,我的 JTables 是分页的,它只显示一个数据范围。现在我想处理排序但服务器端。如何自定义默认排序实现?

4

1 回答 1

1

我找到了一个可行的解决方案,但我确信它不是最好的!:)

...
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;
  }
}
于 2012-04-26T21:00:35.430 回答