bindingscalafx

ScalaFX. Label - How to bind IntegerProperty?


I have a simple form for example:

object Main extends JFXApp {
    stage = new PrimaryStage() {
        title = "My Form"
        scene = new Scene {
            root = new Label { text <== ViewModel.intProp }
        }
    }
}

And a simple example ViewModel:

object ViewModel {
  //Some mutable integer property. I want to keep it as IntegerProperty, not StringProperty
  val intProp = IntegerProperty(10)

  intProp.value = 15
}

How to bind my IntegerProperty to my Label, which expects StringProperty?


Solution

  • Edited: I was forgetting about .asString. Doh!

    You can simply bind the property as follows:

    Main.scala:

    object Main extends JFXApp {
      stage = new PrimaryStage() {
        title = "My Form"
        scene = new Scene {
    
          // Bind label to int property as a string.
          root = new Label {
            text <== ViewModel.intProp.asString
          }
        }
      }
    }
    

    ViewModel.scala:

    object ViewModel {
      val intProp = IntegerProperty(10)
    
      intProp.value = 15
    }