Packages

  • package root

    Helper methods and classes to simplify ScalaFX use.

    Helper methods and classes to simplify ScalaFX use.

    Package org.scalafx.extras contains basic helper methods for running tasks on threads and showing messages.

    Package org.scalafx.extras.image contains image display component with scrolling and zooming.

    Package org.scalafx.extras.mvcfx contains classes for creating with UI components based on FXML.

    Definition Classes
    root
  • package org
    Definition Classes
    root
  • package scalafx
    Definition Classes
    org
  • package extras

    Helper methods for working with ScalaFX.

    Helper methods for working with ScalaFX.

    Definition Classes
    scalafx
  • package image
    Definition Classes
    extras
  • package mvcfx

    Package mvcfx helps in implementation of Model-View-Controller-like patters, we call it MVCfx.

    Package mvcfx helps in implementation of Model-View-Controller-like patters, we call it MVCfx. The pattern is build around use of views defined in FXML (the view), with binding to ScalaFX using ScalaFXML library.

    There are two cooperating classes ControllerFX for binding FXML to Scala code and ModelFX that contains logic for the component. An additional helper MVCfx class is provided to instantiate the ControllerFX and the corresponding ModelFX.

    The structure of the UI component is defined in a standard JavaFX FXML file. The Scala side of the FXML is in a class ControllerFX. Part of the ControllerFX is automatically generated by ScalaFXML macro, the rest can be customized as needed, including binding of the UI to appropriate parts of the component logic represented by the ModelFX. Use of the MVCfx is optional and primarily intended to simplify instantiation of the ControllerFX and the ModelFX.

    Below is an example using the classes in mvcfx. The code implements a simple Stop Watch. The complete code is in demos part of the ScalaFX Extras project.

    Note the recommended naming convention used: * StopWatch extends MVCfx * StopWatchModel extends ModelFX * StopWatchController extends ControllerFX * StopWatch.fxml the FXVM declaration of the view

    First we have the FXML definitions representing the structure of the user interface (org/scalafx/extras/mvcfx/stopwatch/StopWatch.fxml)

    <?import javafx.geometry.Insets?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.BorderPane?>
    <?import javafx.scene.layout.HBox?>
    <?import javafx.scene.text.*?>
    <BorderPane xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1"
                fx:controller="org.scalafx.extras.mvcfx.stopwatch.StopWatchController">
        <bottom>
            <ButtonBar BorderPane.alignment="CENTER">
                <buttons>
                    <Button fx:id="startButton" mnemonicParsing="false" text="Start"/>
                    <Button fx:id="stopButton" mnemonicParsing="false" text="Stop"/>
                    <Button fx:id="resetButton" mnemonicParsing="false" text="Reset"/>
                </buttons>
            </ButtonBar>
        </bottom>
        <center>
            <HBox>
                <children>
                    <Label fx:id="minutesLabel" alignment="CENTER" contentDisplay="CENTER" text="99" textAlignment="CENTER"
                           BorderPane.alignment="CENTER">
                    </Label>
                    <Label text=":">
                    </Label>
                    <Label fx:id="secondsLabel" alignment="CENTER" contentDisplay="CENTER" text="99" textAlignment="CENTER">
                    </Label>
                    <Label text=".">
                    </Label>
                    <Label fx:id="fractionLabel" alignment="CENTER" contentDisplay="CENTER" text="99"
                           textAlignment="CENTER">
                    </Label>
                </children>
            </HBox>
        </center>
    </BorderPane>

    The ControllerFX creates connection of the FXML to Scala code and underlying ModelFX for the application logic. Note the @sfxml annotation and the constructor arguments corresponding to controls defined in FXML, like minutesLabel. The last argument to the constructor is the ModelFX. (org.scalafx.extras.mvcfx.stopwatch.StopWatchController)

    package org.scalafx.extras.mvcfx.stopwatch
    
    import org.scalafx.extras.mvcfx.ControllerFX
    
    import scalafx.Includes._
    import scalafx.scene.control.{Button, Label}
    import scalafxml.core.macros.sfxml
    
    @sfxml
    class StopWatchController(minutesLabel: Label,
                              secondsLabel: Label,
                              fractionLabel: Label,
                              startButton: Button,
                              stopButton: Button,
                              resetButton: Button,
                              model: StopWatchModel) extends ControllerFX {
    
      minutesLabel.text.value = format2d(model.minutes.longValue)
      model.minutes.onChange { (_, _, newValue) =>
        minutesLabel.text.value = format2d(newValue.longValue)
      }
      secondsLabel.text.value = format2d(model.seconds.longValue())
      model.seconds.onChange { (_, _, newValue) =>
        secondsLabel.text.value = format2d(newValue.longValue())
      }
      fractionLabel.text.value = format2d(model.secondFraction.longValue() / 10)
      model.secondFraction.onChange { (_, _, newValue) =>
        fractionLabel.text.value = format2d(newValue.longValue() / 10)
      }
    
      startButton.disable <== model.running
      stopButton.disable <== !model.running
      resetButton.disable <== model.running
    
      startButton.onAction = handle {
        model.onStart()
      }
      stopButton.onAction = handle {
        model.onStop()
      }
      resetButton.onAction = handle {
        model.onReset()
      }
    
      private def format2d(t: Number) = f"${t.longValue()}%02d"
    }

    The ModelFX implements the logic for the operation of the Stop Watch. Notice that there are no direct references to UI controls. The connection to the UI is through the properties (like minutes). The ModelFX is not aware how the ControllerFX is implemented. (org.scalafx.extras.mvcfx.stopwatch.StopWatchModel)

    package org.scalafx.extras.mvcfx.stopwatch
    
    import javafx.{concurrent => jfxc}
    
    import org.scalafx.extras._
    import org.scalafx.extras.mvcfx.ModelFX
    
    import scalafx.Includes._
    import scalafx.beans.property.{LongProperty, ReadOnlyBooleanProperty, ReadOnlyBooleanWrapper}
    
    class StopWatchModel extends ModelFX {
    
      private val _running = ReadOnlyBooleanWrapper(false)
    
      val running: ReadOnlyBooleanProperty = _running.readOnlyProperty
    
      private val counterService = new CounterService()
      counterService.period = 10.ms
    
      val minutes = new LongProperty()
      val seconds = new LongProperty()
      val secondFraction = new LongProperty()
    
      counterService.elapsedTime.onChange { (_, _, newValue) =>
        val t = newValue.longValue()
        secondFraction.value = t % 1000
        seconds.value = (t / 1000) % 60
        minutes.value = t / 1000 / 60
      }
    
      def onStart(): Unit = {
        counterService.doResume()
        _running.value = true
      }
    
      def onStop(): Unit = {
        counterService.doPause()
        _running.value = false
      }
    
      def onReset(): Unit = counterService.doReset()
    
      private class CounterService extends jfxc.ScheduledService[Long] {
    
        private var timeAccumulator: Long = 0
        private var restartTime: Long = 0
    
        val elapsedTime = new LongProperty()
    
        override def createTask(): jfxc.Task[Long] = {
          new jfxc.Task[Long]() {
            override protected def call(): Long = {
              val ct = System.currentTimeMillis()
              val et = timeAccumulator + (ct - restartTime)
              onFX {elapsedTime.value = et}
              et
            }
          }
        }
    
        def doPause(): Unit = {
          val ct = System.currentTimeMillis()
          timeAccumulator += (ct - restartTime)
          onFX {elapsedTime.value = timeAccumulator}
          this.cancel()
        }
    
        def doResume(): Unit = {
          restartTime = System.currentTimeMillis()
          this.restart()
        }
    
        def doReset(): Unit = {
          timeAccumulator = 0
          onFX {elapsedTime.value = 0}
        }
      }
    }

    The MVCfx implementation is very simple, it only needs instance of the model and information about location of the FXML resource. (org.scalafx.extras.mvcfx.stopwatch.StopWatch)

    package org.scalafx.extras.mvcfx.stopwatch
    
    import org.scalafx.extras.mvcfx.MVCfx
    
    class StopWatch(val model: StopWatchModel = new StopWatchModel())
      extends MVCfx("/org/scalafx/extras/mvcfx/stopwatch/StopWatchView.fxml")

    The MVCfx can be easily used in an Application class to create UI. (org.scalafx.extras.mvcfx.stopwatch.StopWatchApp)

    package org.scalafx.extras.mvcfx.stopwatch
    
    import scala.language.implicitConversions
    import scalafx.application.JFXApp
    import scalafx.application.JFXApp.PrimaryStage
    import scalafx.scene.Scene
    import scalafx.scene.layout.BorderPane
    
    object StopWatchApp extends JFXApp {
      stage = new PrimaryStage {
        scene = new Scene {
          title = "StopWatch"
          root = new BorderPane {
            center = new StopWatch().view
          }
        }
      }
    }
    Definition Classes
    extras
  • package pong
    Definition Classes
    extras
  • BusyWorker
  • ShowMessage
  • ShowMessageLogger

class BusyWorker extends ShowMessage

BusyWorker helps running UI tasks a separate threads (other than the JavaFX Application thread). It will show busy cursor and disable specified nodes while task is performed. It gives an option to show progress and status messages. BusyWorker run tasks and takes care of handling handling exceptions and displaying error dialogs. There is also option to perform custom finish actions after task is completed.

While task is performed property busy is set to true. Only one task, for a given worker, can be run at the time. When a task in being performed busyDisabledNode will be disabled and its cursor will be set to Wait/Busy cursor.

Progress and messages from the running task can be monitored using progressValue and progressMessage properties.

Below is an example of using using BusyWorker that updates a progress message and progress indicator. The full example can be found in the BusyWorkerDemo of the ScalaFX Extras Demo project.

val buttonPane: Pane = ...
val progressLabel: Label = ...
val progressBar: ProgressBar = ...

val busyWorker = new BusyWorker("BusyWorker Demo", buttonPane) {
  progressLabel.text <== progressMessage
  progressBar.progress <== progressValue
}

val button = new Button("Click Me") {
      onAction = () => busyWorker.doTask("Task 1")(
        new SimpleTask[String] {
          override def call(): String = {
            val maxItems = 10
            for (i <- 1 to maxItems) {
              println(i)
              message() = s"Processing item $i/$maxItems"
              progress() = (i - 1) / 10.0
              Thread.sleep(250)
            }
            progress() = 1
            "Done"
          }
        }
      )
}
Source
BusyWorker.scala
Linear Supertypes
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. BusyWorker
  2. ShowMessage
  3. AnyRef
  4. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Instance Constructors

  1. new BusyWorker(title: String, disabledNodes: Seq[Node])

    Creates a busy worker with a title and nodes to disable when performing tasks.

    Creates a busy worker with a title and nodes to disable when performing tasks. The parent window is the parent window of the first node.

    The input is a collection of JavaFX or ScalaFX nodes.

    val nodes = Seq[scalafx.scene.Node] = ...
    val busyWorker = new BusyWorker("My Task", nodes))
    title

    title used for unexpected error dialogs.

    disabledNodes

    nodes that will be disabled when performing a task, if not specified it will be set to root pane of the parentWindow.

  2. new BusyWorker(title: String, disabledNode: Node)

    Creates a busy worker with a title and nodes to disable when performing tasks.

    Creates a busy worker with a title and nodes to disable when performing tasks. The parent window is the parent window of the node.

    The input is a collection of JavaFX or ScalaFX nodes.

    val node: scalafx.scene.Node] = ...
    val busyWorker = new BusyWorker("My Task", node))
    title

    title used for unexpected error dialogs.

    disabledNode

    node that will be disabled when performing a task, cannot be null.

  3. new BusyWorker(title: String, parent: Option[Window])

    Creates a busy worker with a title and nodes to disable when performing tasks.

    Creates a busy worker with a title and nodes to disable when performing tasks. The root node of the parentWindow will be disabled when task is being executed.

    The input is a collection of JavaFX or ScalaFX nodes.

    val parent: Option[Window] = ...
    val busyWorker = new BusyWorker("My Task", parent))
    title

    title used for unexpected error dialogs.

    parent

    window that will be used to display dialogs (if any).

  4. new BusyWorker(title: String, parent: Window)

    Creates a busy worker with a title and nodes to disable when performing tasks.

    Creates a busy worker with a title and nodes to disable when performing tasks. The root node of the parentWindow will be disabled when task is being executed.

    The input is a collection of JavaFX or ScalaFX nodes.

    val parent: Window = ...
    val busyWorker = new BusyWorker("My Task", parent))
    title

    title used for unexpected error dialogs.

    parent

    window that will be used to display dialogs (if any).

Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. final def ##(): Int
    Definition Classes
    AnyRef → Any
  3. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  4. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  5. final val busy: BooleanProperty

    busy property is true when worker is performing a task.

    busy property is true when worker is performing a task. Only one task can be done at a time.

  6. def clone(): AnyRef
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native() @HotSpotIntrinsicCandidate()
  7. def disabledNodes: Seq[Node]
  8. def disabledNodes_=(implicit v: Seq[Node]): Unit
  9. def doTask[R](name: String)(task: SimpleTask[R]): Future[R]

    Run a task on a separate thread.

    Run a task on a separate thread. Returns immediately (before task is completed). If the task returns a value is can be retrieved through the returned Future.

    Example of running a task without waiting to complete, using a lambda

    worker.doTask("My Task") { () =>
       // Some workload code, does not produce value ot it is discard
       Thread.sleep(1000)
       print(1 + 1)
    }

    Example of stating a task (with a lambda) and waiting till it finishes and returns a result

    // This code will return before workload is completed
    val future = worker.doTask("My Task") { () =>
       // Some workload code producing final value
       Thread.sleep(1000)
       1 + 1
    }
    // This will block till workload competes and the result is retrieved
    val result = future.get()
    print(result)

    Example of running task that updates progress and message, for more details see BusyWorkerDemo.

    busyWorker.doTask("Task 1")(
             new SimpleTask[String] {
               override def call(): String = {
                 val maxItems = 10
                 for (i <- 1 to maxItems) {
                   println(i)
                   message() = s"Processing item $i/$maxItems"
                   progress() = (i - 1) / 10.0
                   Thread.sleep(250)
                 }
                 progress() = 1
                 "Done"
               }
             }
           )
    name

    name used for thread that runs the task. May be useful in debugging.

    task

    actions to perform, can be provided a as a lambda op: => R, see examples above.

    returns

    Future that can be used to retrieve result produced the workload, if any.

  10. def doTask[R](task: SimpleTask[R]): Future[R]

    Run a task on a separate thread.

    Run a task on a separate thread. Returns immediately (before task is completed). If the task returns a value is can be retrieved through the returned Future.

    Example of running a task without waiting to complete, using a lambda

    worker.doTask{ () =>
       // Some workload code, does not produce value ot it is discard
       Thread.sleep(1000)
       print(1 + 1)
    }

    Example of stating a task (with a lambda) and waiting till it finishes and returns a result

    // This code will return before workload is completed
    val future = worker.doTask{ () =>
       // Some workload code producing final value
       Thread.sleep(1000)
       1 + 1
    }
    // This will block till workload competes and the result is retrieved
    val result = future.get()
    print(result)

    Example of running task that updates progress and message, for more details see BusyWorkerDemo.

    busyWorker.doTask(
             new SimpleTask[String] {
               override def call(): String = {
                 val maxItems = 10
                 for (i <- 1 to maxItems) {
                   println(i)
                   message() = s"Processing item $i/$maxItems"
                   progress() = (i - 1) / 10.0
                   Thread.sleep(250)
                 }
                 progress() = 1
                 "Done"
               }
             }
           )
    task

    actions to perform, can be provided a as a lambda op: => R, see examples above.

    returns

    Future that can be used to retrieve result produced the workload, if any.

  11. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  12. def equals(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  13. final def getClass(): Class[_]
    Definition Classes
    AnyRef → Any
    Annotations
    @native() @HotSpotIntrinsicCandidate()
  14. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native() @HotSpotIntrinsicCandidate()
  15. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  16. def messageLogger: Option[ShowMessageLogger]

    Logger to use for error and warning dialogs.

    Logger to use for error and warning dialogs.

    Attributes
    protected
    Definition Classes
    ShowMessage
  17. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  18. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native() @HotSpotIntrinsicCandidate()
  19. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native() @HotSpotIntrinsicCandidate()
  20. def parentWindow: Option[Window]

    Parent window for a dialog.

    Parent window for a dialog. Dialogs are shown modal, the window will be blocked while dialog is displayed.

    Definition Classes
    BusyWorkerShowMessage
  21. def parentWindow_=(v: Window): Unit
  22. def parentWindow_=(v: Option[Window]): Unit
  23. final val progressMessage: ReadOnlyStringProperty

    Progress message posted by running task, if any.

    Progress message posted by running task, if any. Current running task's message property is bound to this property (only when task is running).

  24. final val progressValue: ReadOnlyDoubleProperty

    Progress indicator of a running task, if any, value are between [0 and 1].

    Progress indicator of a running task, if any, value are between [0 and 1]. Current running task's progress property is bound to this property (only when task is running).

  25. def showConfirmation(title: String, header: String, content: String = ""): Boolean

    Show a confirmation dialog with "OK" and "Cancel" buttons.

    Show a confirmation dialog with "OK" and "Cancel" buttons.

    title

    dialog title.

    header

    header text.

    content

    content text.

    returns

    true when user selected 'OK' and false when user selected Cancel or dismissed the dialog.

    Definition Classes
    ShowMessage
  26. def showConfirmationYesNoCancel(title: String, header: String, content: String = ""): Option[Boolean]

    Show a confirmation dialog with "OK", "No", and "Cancel" buttons.

    Show a confirmation dialog with "OK", "No", and "Cancel" buttons.

    title

    dialog title.

    header

    header text.

    content

    content text.

    returns

    Some(true) when user selected 'OK', Some(false) when user selected No, and None user selected Cancel or dismissed the dialog.

    Definition Classes
    ShowMessage
  27. def showError(title: String, header: String, content: String = ""): Unit

    Show error dialog

    Show error dialog

    title

    dialog title

    header

    header text.

    content

    main content text.

    Definition Classes
    ShowMessage
  28. def showException(title: String, message: String, t: Throwable): Unit

    Displays error dialog with expandable exception information.

    Displays error dialog with expandable exception information.

    title

    Dialog title

    message

    Message (excluding t.getMessage(), it is automatically displayed)

    t

    exception to be displayed in the dialog

    Definition Classes
    ShowMessage
  29. def showInformation(title: String, header: String, content: String): Unit

    Show information dialog

    Show information dialog

    title

    dialog title

    header

    header text.

    content

    main content text.

    Definition Classes
    ShowMessage
  30. def showWarning(title: String, header: String, content: String): Unit

    Show warning dialog

    Show warning dialog

    title

    dialog title

    header

    header text.

    content

    main content text.

    Definition Classes
    ShowMessage
  31. final def synchronized[T0](arg0: ⇒ T0): T0
    Definition Classes
    AnyRef
  32. val title: String
  33. def toString(): String
    Definition Classes
    AnyRef → Any
  34. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  35. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  36. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )

Deprecated Value Members

  1. def finalize(): Unit
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] ) @Deprecated @deprecated
    Deprecated

    (Since version ) see corresponding Javadoc for more information.

Inherited from ShowMessage

Inherited from AnyRef

Inherited from Any

Ungrouped