câu trả lời
Marco Jakob là tốt cho hầu hết các trường hợp, nhưng tôi thấy rằng tôi cần thiết để tạo ra một so sánh phù hợp thứ tự sắp xếp bảng để linh hoạt hơn. Sau đó, bạn có thể sử dụng bất kỳ phương pháp nào để so sánh để phân loại, tìm kiếm, v.v. Để tạo bộ so sánh, tôi mở rộng lớp ComparatorChain từ Bộ sưu tập chung của apache để dễ dàng phân loại nhiều cột. Nó trông như thế này
public class TableColumnListComparator extends ComparatorChain {
public TableColumnListComparator(ObservableList<? extends TableColumn> columns) {
// Get list of comparators from column list.
for (TableColumn column : columns) {
addComparator(new ColumnComparator(column));
}
}
/**
* Compares two items in a table column as if they were being sorted in the TableView.
*/
private static class ColumnComparator implements Comparator {
private final TableColumn column;
/**
* Default Constructor. Creates comparator based off given table column sort order.
*
* @param column
*/
public ColumnComparator(TableColumn column) {
this.column = column;
}
@Override
public int compare(Object o1, Object o2) {
// Could not find a way to do this without casts unfortunately
// Get the value of the column using the column's cell value factory.
final ObservableValue<?> obj1 = (ObservableValue) column.getCellValueFactory().call(
new TableColumn.CellDataFeatures(column.getTableView(), column, o1));
final ObservableValue<?> obj2 = (ObservableValue) column.getCellValueFactory().call(
new TableColumn.CellDataFeatures(column.getTableView(), column, o2));
// Compare the column values using the column's given comparator.
final int compare = column.getComparator().compare(obj1.getValue(), obj2.getValue());
// Sort by proper ascending or descending.
return column.getSortType() == TableColumn.SortType.ASCENDING ? compare : -compare;
}
}
}
Bạn có thể sau đó sắp xếp bất cứ lúc nào với
Collections.sort(backingList, new TalbeColumnListComparator(table.getSortOrder());
Tôi sử dụng này để sắp xếp nhiều danh sách với cùng một loại, sắp xếp trên chủ đề nền, làm cập nhật hiệu quả mà không cần toàn bộ danh sách, vv Tôi nghĩ rằng sẽ có một số cải tiến đối với việc sắp xếp bảng trong Javafx 8 vì vậy điều này sẽ không cần thiết trong tương lai.
Nguồn
2013-09-23 18:24:21
độc giả tương lai:!. Tiết kiệm cho mình một chút thời gian và [di chuyển xuống] (http://stackoverflow.com/a/29743777/309308) –