将属性绑定到从JavaFx/TornadoFX中的控件派生的值的正确方式



考虑下面的(kotlin/tornadofx(示例,该示例旨在通过绑定将文本字段的内容与标签的文本连接起来。标签应该反映文本字段的派生值,在本例中是散列。如何正确地实现这种绑定(我觉得使用changelistener不是正确的方法(。

class HashView : View("My View") {
val hashProperty = SimpleStringProperty("EMPTY")
override val root = vbox {
textfield {
hashProperty.bind(stringBinding(text) { computeHash(text)}) // This does not work
}
label(hashProperty)
}
}

附言:java/JavaFX中的答案也很受欢迎,只要我能以某种方式将这个想法应用到龙卷风x中。

UPDATE 1:我发现只有一个小的更改才能使我的示例工作,即它应该是

hashProperty.bind(stringBinding(textProperty() { computeHash(this.value) })

然而,我仍然不确定这是否是传统的方法。所以我将把这个问题留给大家。

我建议在计算中不要涉及实际输入元素的属性。您应该首先定义input属性,并将其绑定到文本字段。然后创建一个派生的StringBinding并将其绑定到标签。还要注意,一个属性有一个内置的stringBinding函数,它会自动对该属性进行操作。这使你的代码看起来更干净,如果需要的话可以重复使用,并且更容易维护:

class HashView : View("My View") {
val inputProperty = SimpleStringProperty()
val hashProperty = inputProperty.stringBinding { computeHash(it ?: "EMPTY") }
override val root = vbox {
textfield(inputProperty)
label(hashProperty)
}
fun computeHash(t: String) = "Computed: $t"
}

在JavaFX中,您可以使用StringConverter:

TextField field = new TextField();
Label label = new Label();
label.textProperty().bindBidirectional(field.textProperty(), new StringConverter<String>() {
@Override
public String toString(String fieldValue) {
// Here you can compute the hash
return "hash(" + fieldValue+ ")";
}
@Override
public String fromString(String string) {
return null;
}
});

最新更新