JavaFX绑定SimpleLongProperty到Label并格式化字节为可读文件大小
实现方案
完全可以在绑定逻辑中调用你已实现的humanReadableByteCount方法完成数值格式化。你之前使用的Bindings.format仅支持占位符默认格式化规则,无法嵌入自定义值转换逻辑,替换为Bindings.createStringBinding构造自定义字符串绑定即可,该方式会自动监听依赖属性的变化,实时更新标签显示内容。
修改绑定逻辑
将initialize方法中的原有绑定替换为如下代码即可:
@Override public void initialize(URL url, ResourceBundle resourceBundle) { deletedFilesLabel.textProperty().bind(Bindings.createStringBinding(() -> { int deletedCount = deletedFilesCount.get(); long deletedSize = deletedFilesSize.get(); // 第二个参数传true使用1000进制SI单位,1000000字节对应1MB;传false为1024进制,显示为1MiB String readableSize = humanReadableByteCount(deletedSize, true); return String.format("Deleted files: %d (%s)", deletedCount, readableSize); }, deletedFilesCount, deletedFilesSize)); }
注意:
createStringBinding的第二个及后续参数为绑定依赖的属性列表,必须把用到的deletedFilesCount、deletedFilesSize两个属性传入,否则属性值变更时标签不会自动刷新。
格式化逻辑微调(可选)
你当前实现的humanReadableByteCount使用%.1f格式化数值,1000000字节会输出1.0 MB,如果要和示例一致显示无小数的1MB,可以把方法内的返回逻辑稍作调整,整数结果省略小数位:
public static String humanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); double sizeValue = bytes / Math.pow(unit, exp); if (sizeValue == (long) sizeValue) { return String.format("%d %sB", (long) sizeValue, pre); } return String.format("%.1f %sB", sizeValue, pre); }
内容的提问来源于stack exchange,提问作者kanka.dev
相关产品推荐
相关产品推荐

