简体   繁体   English

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

[英]JavaFX: Bind SimpleLongProperty to a Label and format long value to human readable filesize

I have a Label which is binded to two Properties.我有一个绑定到两个属性的标签。 The first value (deletedFilesCountProperty) is a simple int without needing for formatting.第一个值 (deletedFilesCountProperty) 是一个简单的 int,不需要格式化。 But how can I format the second property (SimpleLongProperty) to a human readable filesize value?但是如何将第二个属性(SimpleLongProperty)格式化为人类可读的文件大小值?

Example: deletedFilesSize 's value is 1000000. The label should show "1MB" instead.示例: deletedFilesSize的值为 1000000。标签应改为显示“1MB”。

Can I call the humanReadableByteCount function inside the Binding to let this function format the value?我可以在 Binding 中调用humanReadableByteCount函数来让这个函数格式化值吗?

My code so far:到目前为止我的代码:

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);
    }
}

Thanks.谢谢。

Use Bindings.createStringBinding(...) .使用Bindings.createStringBinding(...) A simple example would look like:一个简单的示例如下所示:

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

Your specific example would look something like:您的具体示例如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM