Search code examples
scalajavafxscalafx

Pass data to a ScalaFX JFXApp


I wrote a GUI in ScalaFX whichs works quite well when testing it isolated. Things to mention:

  • The "real" application itself already has a main method, and only that one should be used to start the application, not the one I get when extending JFXApp. So the call to the main method of JFXApp is done manually, from the outside
  • It should be possible to pass a data structure to the JFXApp, so I added a setter

The whole startup procedure looks like this:

def main(args: Array[String]) {
    ...
    ...
    JFXGui.setData(data)
    JFXGui.main(Array())
}

The problem:

  • I cannot draw the contents of the data object as long as the main method of the JFX object is not called, so setData is really just a simple setter method. The idea is that JFXGui should draw the data as soon as possible after JFXGui.main was called. But: how can I realize this inside of JFXGui? Is there something like an "onready"-method?
  • In the above code, I tried to put the call to the setter after the call to the main method, so that the setter can trigger the drawing. What I hadn't in mind is that JFXGui.main is blocking forever, therefore the call to the setter is unreachable code.

How could I fix this? any help is appreciated, thanks.

edit:

JFXGui is the name of my ScalaFX UI:

object JFXGui extends JFXApp {

  private var data: Data = _

  def setData(data: Data) {
    this.data = data;
 }

  // tons of ScalaFX related things which visualize the data object
  // ...
}

Solution

  • Solution 1 (reusing JFXApp)

    The Gui object no longer should be an object, but a class with constructor parameters.

    class Gui(data: Data) extends JFXApp {
        //your existing code without the field data and the method setData()
    }
    

    In the startup class:

    new Gui(data).main(Array())
    

    Solution 2 (Custom init)

    You do not necessarily have to use JFXApp in order to run your application. I suggest you having a look at the source code of JFXApp.main() and the class AppHelper. They contain ~10 lines of code combined so you can just copy their source code and tailor it to your needs.