0

I just started to write scalafx application and have a question about bindings.

I have an Enumeration with connection status in my presenter class and I want to select appropriate icon in label in view class. I basically can create binding in javafx way and set converter which will select appropriate ImageView every time status changes, but is it possible to do in ScalaFX way?

I looked many scalafx examples, but still can't find anything like this.

Here is some code:

package view

import scalafx.beans.property.ObjectProperty

class MainWindowPresenter {
  object DatabaseState extends  Enumeration {
    type DatabaseState = Value
    val NOT_CONNECTED, IDLE, BUSY, ERROR = Value
  }

  val login = new ObjectProperty[String](this, "login", "awesomeloginname")
  val state = new ObjectProperty[DatabaseState.DatabaseState](this, "state", DatabaseState.ERROR)
}

View class:

package view

import java.util.concurrent.Callable
import javafx.beans.binding.ObjectBinding

import collection.immutable.HashMap

import javafx.scene.control.SeparatorMenuItem

import scala.util.Random
import scalafx.beans.property.{ObjectProperty}
import scalafx.geometry.{Orientation, Insets, Pos}
import scalafx.scene.control._
import scalafx.scene.image.{ImageView, Image}
import scalafx.scene.layout._

import scalafx.Includes._

class MainWindowView extends BorderPane {
  val model = new MainWindowPresenter

  top = new HBox {
    content = List(
      new Label() {
       graphic <== //somehow select imageview depending on model.state
      }
    )
  }

  private def imageFromResource(name : String) =
    new ImageView(new Image(getClass.getClassLoader.getResourceAsStream(name)))
}

Thanks in advance and sorry for grammar mistakes, if any - English isn't my native.

rtgbnm
  • 33
  • 6

1 Answers1

0

You can use EasyBind or the snapshot (2.0-SNAPSHOT) version of ReactFX to create the binding. Both are Java libraries, but they are easy to use from Scala. This is the EasyBind way:

graphic <== EasyBind.map(model.state, stateToImage)

val stateToImage: Function1[DatabaseState.DatabaseState, ImageView] = {
  // convert state to ImageView
}

This code uses the implicit conversion from Scala's Function1 to Java's Function.

You could also define an implicit conversion from ScalaFX ObjectProperty to EasyBind's MonadicObservableValue and then the first line above can be rewritten to:

graphic <== model.state.map(stateToImage)
Tomas Mikula
  • 6,537
  • 25
  • 39
  • Thanks! I used EasyBind solution for now, but ReactFX looks much more interesting, I think I'll use it for future code. – rtgbnm Feb 01 '15 at 16:03
  • ReactFX 2.0 is going to absorb all the functionality from EasyBind, and most of it is already there in the snapshot release, but it is not yet documented. So yes, I suggest using ReactFX for the future. – Tomas Mikula Feb 01 '15 at 23:58