我正在尝试对包含 3 列的 JavaFX TableView
进行排序,一列是日期,一列是名称(字符串),最后一列是标签列(这是一个枚举)。我想要做的是,无论表格当前在哪一列排序,行都将首先按标签排序(如果它有某个标签,它会排在行上方没有那个特定标签)。
因此按名称升序搜索时,表的顺序如下:
- “乔治”[标签]
- 'ZZ' [标签]
- “苹果”[无标签]
- “你好”[无标签]
等等
我查看了列比较器,但是我似乎只能指定该列类型,即我希望能够指定名称列比较器以接收整行的类对象,以及名称-列数据类型(字符串),因此我可以访问该类实例中的标签 - 但是在网上查看后这似乎不可能。
是否也可以坚持这个规则,即使选择标签列来排序 desc(所以它仍然首先放置带有标签的行)。如果不是,我可以只禁用标签列的排序
提前感谢任何能给我指出正确方向的人
最佳答案
正如我在评论中提到的,您不能只创建一个绑定(bind),它包装 TableView 的比较器并将其提供给 SortedList。此外,SortedList 是 final
,因此您无法扩展它。使用自定义 TransformationList
也不起作用,因为 TableView
有一些以 if (itemsList instanceof SortedList)
开头的硬编码内容。
这就是我最终得到的结果(为了清楚起见,使用 java7 格式而不是 labdas):
filteredList = new FilteredList<>(yourOriginalList);
table.sortPolicyProperty().set(new Callback<TableView<YourObject>, Boolean>() {
@Override
public Boolean call(TableView<YourObject> param) {
final Comparator<YourObject> tableComparator = transactionTable.getComparator();
// if the column is set to unsorted, tableComparator can be null
Comparator<YourObject> comparator = tableComparator == null ? null : new Comparator<YourObject>() {
@Override
public int compare(YourObject o1, YourObject o2) {
// first sort by your tag
final int tagCompare = o1.getTag().compareTo(o2.getTag());
if (tagCompare == 0) {
// secondly sort by the comparator that was set for the table
return tableComparator.compare(o1, o2);
}
return tagCompare;
}
};
table.setItems(filteredList.sorted(comparator));
return true;
}
});
// you may also need to call
table.setItems(filteredList.sorted(transactionTable.getComparator()));
关于JavaFX Tableview 按自定义规则排序,然后按列选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50109815/