这是我目前拥有的:
fileSizeColumn.setCellValueFactory(cellData -> {
SimpleStringProperty stringProperty = new SimpleStringProperty();
float sizeInMegabytes = (float)cellData.getValue().fileSizeProperty().getValue() / 1024 / 1024;
sizeInMegabytes = round(sizeInMegabytes, 2);
stringProperty.setValue(sizeInMegabytes + "mb");
return stringProperty;
});
fileSizeColumn.setComparator((t1, t2) -> {
float f1 = Float.parseFloat(t1.replaceAll("[^0-9.]",""));
float f2 = Float.parseFloat(t2.replaceAll("[^0-9.]",""));
return Float.compare(f1,f2);
});
因此有一个文件大小的属性,最初是 long
(以字节为单位)。为了将其放入我的表中,我将其转换为兆字节,四舍五入到小数点后两位,然后添加 "mb"
在最后。然后我制作了一个自定义比较器来剥离 "mb"
结束了。我最终将根据大小以 KB 和 GB 为单位,这将使比较器变得笨重(如果 endsWith("mb")
执行此操作,如果 endsWith("kb")
执行此操作等)。
我想要的是将 long 添加到表中作为 SimpleLongProperty
但以某种方式格式化它的显示方式。
那么是否有任何选项可以说“这是应该用于排序的幕后实际值,现在取这个值,将其除以一个数字,并将字符串“mb”添加到末尾实际显示时它”?
谢谢
最佳答案
通常,您将数据以其原始形式保存在 cellValueFactory
中,并使用 cellFactory
自定义 TableCell
来自定义数据的存储方式显示:
public static String fileSizeToText(long fileSize) {
return round(((float) fileSize) / 1024 / 1024, 2) + "mb";
}
...
TableColumn<MyClass, Number> fileSizeColumn = ...
fileSizeColumn.setCellValueFactory(cellData -> cellData.getValue().fileSizeProperty());
fileSizeColumn.setCellFactory(c -> new TableCell<MyClass, Number>() {
@Override
protected void updateItem(Number item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
} else {
setText(fileSizeToText(item.longValue()));
}
}
});
此方法不需要 Comparator
,因为 Long
以适合您需求的方式实现 Comparable
。
关于JavaFX 表格 View : can I keep column data as a float so it's sortable and format/show it as a string somehow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39157939/