绑定到标签时格式化整数

时间:2018-02-23 14:28:22

标签: java user-interface javafx data-binding number-formatting

我正在尝试格式化整数,同时将其绑定到标签的text属性。

我知道我可以在我的值设置器中使用setText(),但我宁愿以正确的方式完成绑定。

在我的控制器初始化中,我有:

sec = new SimpleIntegerProperty(this,"seconds");
secondsLabel.textProperty().bind(Bindings.convert(sec));

但当秒数低于10时,它显示为一位数,但我希望它保持两位数。所以我尝试将Binding更改为以下内容:

 secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
        NumberFormat formatter = NumberFormat.getIntegerInstance();
        formatter.setMinimumIntegerDigits(2);
        if(sec.getValue() == null) {
            return "";
        }else {
            return formatter.format(sec.get());
        }
    }));

这将对其进行格式化,但是当我覆盖它sec.set(newNumber);时,该值不会改变。

我也试过这个:

secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
            if(sec.getValue() == null) {
                return "";
            }else {
                return String.format("%02d", sec.getValue());
            }
        }));

但那也做了同样的事情。加载精细,显示两位数,但是当通过sec.set(newNumber);更改了数字时没有任何变化。该数字永远不会高于六十或低于零

2 个答案:

答案 0 :(得分:1)

您需要告知绑定,只要sec属性失效,它就会失效。 Bindings.createStringBinding(...)在应该传递绑定需要绑定的任何属性的函数之后获取varargs参数。您可以按如下方式直接调整代码:

secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
    NumberFormat formatter = NumberFormat.getIntegerInstance();
    formatter.setMinimumIntegerDigits(2);
    if(sec.getValue() == null) {
        return "";
    }else {
        return formatter.format(sec.get());
    }
}, sec));

secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
    if(sec.getValue() == null) {
        return "";
    }else {
        return String.format("%02d", sec.getValue());
    }
}, sec));

正如@fabian指出的那样,IntegerProperty.get()永远不会返回null,因此您可以删除空检查并执行:

secondsLabel.textProperty().bind(Bindings.createStringBinding(
    () -> String.format("%02d", sec.getValue()),
    sec));

并且在绑定API中有一个便利版本:

secondsLabel.textProperty().bind(Bindings.format("%02d", sec));

答案 1 :(得分:1)

IntegerProperty继承了许多有用的方法,包括asString

secondsLabel.textProperty().bind(sec.asString("%02d"));