【问题标题】:Proper way to bind a Property to a Value derived from a control in JavaFx / TornadoFX将属性绑定到从 JavaFx / TornadoFX 中的控件派生的值的正确方法
【发布时间】:2018-12-22 08:16:34
【问题描述】:

考虑下面的 (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) })

但是我仍然不确定这是否是传统的方法。因此,我将保留这个问题。

【问题讨论】:

    标签: java javafx data-binding kotlin tornadofx


    【解决方案1】:

    我建议不要在计算中涉及实际输入元素的属性。您应该首先定义输入属性并将其绑定到文本字段。然后创建一个派生的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"
    }
    

    【讨论】:

      【解决方案2】:

      在 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;
              }
      
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-25
        • 2011-08-15
        • 1970-01-01
        • 2010-11-23
        • 1970-01-01
        • 1970-01-01
        • 2011-03-07
        相关资源
        最近更新 更多