将属性绑定到从JavaFx/FX中的控件派生的值的正确方法
考虑下面的(kotlin/tornadofx)示例,该示例旨在通过绑定将textfield的内容与标签的文本连接起来。标签应反映textfield的派生值,在本例中为哈希值。如何正确实现这种绑定(我觉得使用changelistener不是正确的方式) PS:java/JavaFX的答案也很受欢迎,只要我能以某种方式在tornadofx中应用这个想法 更新1:我发现只有一个微小的变化才能使我的示例正常工作,即将属性绑定到从JavaFx/FX中的控件派生的值的正确方法,java,javafx,data-binding,kotlin,tornadofx,Java,Javafx,Data Binding,Kotlin,Tornadofx,考虑下面的(kotlin/tornadofx)示例,该示例旨在通过绑定将textfield的内容与标签的文本连接起来。标签应反映textfield的派生值,在本例中为哈希值。如何正确实现这种绑定(我觉得使用changelistener不是正确的方式) PS:java/JavaFX的答案也很受欢迎,只要我能以某种方式在tornadofx中应用这个想法 更新1:我发现只有一个微小的变化才能使我的示例正常工作,即 hashProperty.bind(stringBinding(textProperty
hashProperty.bind(stringBinding(textProperty() { computeHash(this.value) })
然而,我仍然不确定这是否是传统的做法。所以我将保留这个问题。在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;
}
});
TextField=newtextfield();
标签=新标签();
label.textProperty().bindBidirectional(field.textProperty(),new StringConverter()){
@凌驾
公共字符串到字符串(字符串字段值){
//这里可以计算散列
返回“hash(“+fieldValue+”);
}
@凌驾
公共字符串fromString(字符串字符串){
返回null;
}
});
我建议在计算中不要涉及实际输入元素的属性。您应该首先定义输入属性并将其绑定到textfield。然后创建一个派生的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"
}
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"
}