我有一个绑定到两个属性的标签.第一个值(DeletedFileCountProperty)是一个简单的int,无需格式化.但是,如何将第二个属性(SimpleLongProperty)格式化为人类可读的filesize值?

例子:

我可以调用绑定中的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()
));

Java相关问答推荐

泽西岛:退回到不注射的客户"

是否可以从@ TrustMapping中删除特定方法的基路径?

如果一个子类没有构造函数,超类也没有构造函数,那么为什么我可以构造子类的实例呢?

嵌入式ActiveMQ Artemis Web控制台加载错误

Helidon 4和Http API

try 判断可选参数是否为空时出现空类型安全警告

我可以在MacOS上使用什么Java函数来在适当的设备上以适当的音量播放适当的alert 声音?

在执行流和相关操作时,使用Java泛型为2个方法执行相同的操作,但对象不同

将stringBuilder + forloop转换为stream + map

带有可选部分的Java DateTimeForMatter

插入中的JOOQ序列,设置为VS值

当我在Java中有一个Synchronized块来递增int时,必须声明一个变量Volatile吗?

有没有办法知道在合并中执行了什么操作?

在应用getCellFormula()时,Excel引用中的文件名始终为";[1]";使用Apache POI()

RestTemplate Bean提供OkHttp3ClientHttpRequestFactory不支持Spring Boot 3中的请求正文缓冲

控制器建议异常处理

如何在JSP中从select中获取值并将其放入另一个select

如何用Micrometer&;斯普肯

这是JavaFX SceneBuilder的错误吗?

OpenAPI Maven插件生成错误的Java接口名称