gpt4 book ai didi

JavaFX:将 SimpleLongProperty 绑定(bind)到标签并将长值格式化为人类可读的文件大小

转载 作者:行者123 更新时间:2023-12-02 15:50:47 24 4
gpt4 key购买 nike

我有一个绑定(bind)到两个属性的标签。第一个值 (deletedFilesCountProperty) 是一个简单的 int,不需要格式化。但是如何将第二个属性 (SimpleLongProperty) 格式化为人类可读的文件大小值?

例子:deletedFilesSize 的值为 1000000。标签应改为显示“1MB”。

我可以在 Binding 中调用 humanReadableByteCount 函数让这个函数格式化值吗?

到目前为止我的代码:

public class MainController implements Initializable {
private final SimpleIntegerProperty deletedFilesCount = new SimpleIntegerProperty();
private final SimpleLongProperty deletedFilesSize = new SimpleLongProperty();

@FXML
Label deletedFilesLabel;


@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
deletedFilesLabel.textProperty().bind(Bindings.format("Deleted files: %d (%d)", deletedFilesCountProperty(), deletedFilesSizeProperty()));
}

/**
* formats a long number to a human readable file size value
* returns something like: 2MB or 4GB and so on instead of very long Long values.
*/
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");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}

谢谢。

最佳答案

使用 Bindings.createStringBinding(...)。一个简单的例子如下:

fileSizeLabel.bind(Bindings.createStringBinding(
() -> humanReadableByteCount(deletedFilesSizeProperty().get(), false),
deletedFilesSizeProperty()
));

您的具体示例如下所示:

deletedFilesLabel.textProperty().bind(Bindings.createStringBinding(
() -> String.format(
"Deleted files: %d (%s)",
deletedFilesCountProperty().get(),
humanReadableByteCount(deletedFilesSizeProperty().get(), false)
),
deletedFilesCountProperty(),
deletedFilesSizeProperty()
));

关于JavaFX:将 SimpleLongProperty 绑定(bind)到标签并将长值格式化为人类可读的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72576728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com