[英]Proper way to bind a Property to a Value derived from a control in 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)
}
}
PS:只要我能以某種方式在Tornadofx中應用該思想,也歡迎使用Java / JavaFX中的答案。
更新1 :我發現只有一個小小的改動就可以使我的示例正常工作,即應該
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;
}
});
我建議不要在計算中包含實際輸入元素的屬性。 您應該先定義輸入屬性,然后將其綁定到文本字段。 然后創建一個派生的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"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.