javafx - 使用自定义 asString 方法将 simpleStringProperty 绑定(bind)到 simpleIntegerProperty

标签 javafx binding

我有一个 simpleIntegerProperty 表示以秒为单位的数量,我想以 hh:mm:ss 格式表示。

我想通过将 Label textProperty 绑定(bind)到 simpleIntegerProperty 来在 Label 中呈现此内容。我知道我可以使用格式字符串执行类似的操作,例如

activeTimeText.textProperty().bind(model.activeTimeSeconds.asString("Seconds: %04d"));

渲染:

Seconds: 0000

那么问题来了,如何实现更复杂的asString转换呢?例如我当前所需的输出(其中数字是秒 simpleIntegerProperty 的函数。):

00:00:00

我已经搜索过类似的问题,因为我觉得这应该很常见。然而还没有找到答案。如果这是重复的,我们深表歉意。

最佳答案

您可以扩展SimpleIntegerProperty来覆盖asString:

class MySimpleIntegerProperty extends SimpleIntegerProperty{

    @Override
    public StringBinding asString(){
         return Bindings.createStringBinding(() -> " hello " + get() ,    this);
    }
}

测试使用:

MySimpleIntegerProperty activeTimeSeconds = new MySimpleIntegerProperty();
activeTimeSeconds.set(7);

SimpleStringProperty activeTimeText = new SimpleStringProperty();
activeTimeText.bind(activeTimeSeconds.asString());
System.out.println(activeTimeText.get());

您当然可以将值处理委托(delegate)给方法:

@Override
public StringBinding asString(){
    return Bindings.createStringBinding(() -> processValue(get()), this);
}

private String processValue(int value){     
    return " hello " + get() ;
}

关于javafx - 使用自定义 asString 方法将 simpleStringProperty 绑定(bind)到 simpleIntegerProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54453266/

相关文章:

java - 如何在javafx中拉伸(stretch)图像以使其适合整个屏幕

java - 如何根据 JavaFX 中的组合框选择对按钮执行多个操作

JavaFX 如何区分 keyPressed X 和 Keys X + Y 的组合

c# - 将 DatagridComboboxColumn 绑定(bind)到集合

java - 如何将 TreeTableView 列中的文本居中?

java - 如何在 JavaFX 表格 View 中添加按钮

c# - 如何在 Xamarin.Forms 的选项卡式页面中的页面之间共享值?

c# - 从 ViewModel 更改标签内容 Prop

wpf - MyContainer 派生自 FrameworkElement,具有绑定(bind)支持

c# - 在 WPF 中绑定(bind)两个依赖属性