我得到了一个丑陋的解决方案,只能解决一半的问题。我可以将侦听器附加到列标题单击事件,但不能删除默认的 TableView 排序行为。
private void initTable() {
...
...
//listen to sorting type (ASC/DESC) change
SortTypeChangeListener sortTypeChangeListener = new SortTypeChangeListener();
clmName.sortTypeProperty().addListener(sortTypeChangeListener);
clmGender.sortTypeProperty().addListener(sortTypeChangeListener);
reload();
//listen to sortorder change
tblMember.getSortOrder().addListener(new ListChangeListener<TableColumn<VOMember, ?>>() {
@Override
public void onChanged(Change<? extends TableColumn<VOMember, ?>> change) {
reload();
}
});
}
private void reload() {
/**
* Get sorted columns and sorting versus (ASC/DESC)
*/
List<String> lstSortedColumn = new ArrayList<String>();
List<String> lstSortedType = new ArrayList<String>();
for (TableColumn<VOMember, ?> tc : tblMember.getSortOrder()) {
PropertyValueFactory valFactory = (PropertyValueFactory) tc.getCellValueFactory();
valFactory.getProperty();
lstSortedColumn.add(valFactory.getProperty());
lstSortedType.add(tc.getSortType().name());
}
/**
* Retrieve data from database. Pass the sorting information
*/
List<VOMember> lstMember = controller.retrieve(lstSortedColumn, lstSortedType);
ObservableList<VOMember> data = FXCollections.observableList(lstMember);
tblMember.setItems(data);
}
class SortTypeChangeListener implements InvalidationListener {
@Override
public void invalidated(Observable o) {
/**
* If the column is not in sortOrder list, just ignore.
* It avoids intermittent duplicate reload() calling
*/
TableColumn col = (TableColumn) ((SimpleObjectProperty) o).getBean();
if (!tblMember.getSortOrder().contains(col)) {
return;
}
reload();
}
}
我想听听您对此的看法/评论。