从ScalaFX中的后台线程更新UI

时间:2015-09-17 22:04:27

标签: multithreading scala scalafx

以下是代码:

import javafx.event
import javafx.event.EventHandler

import scalafx.application.{Platform, JFXApp}
import scalafx.application.JFXApp.PrimaryStage
import scalafx.event.ActionEvent
import scalafx.scene.Scene
import scalafx.scene.control.{Button, Label}
import scalafx.Includes._
import scalafx.scene.layout.{VBox, HBox}

object Blocking extends JFXApp {
  val statusLbl = new Label("Not started...")
  val startBtn = new Button("Start") {
    onAction = (e: ActionEvent) => startTask
  }
  val exitBtn = new Button("Exit") {
    onAction = (e: ActionEvent) => stage.close()
  }
  val buttonBox = new HBox(5, startBtn, exitBtn)
  val vBox = new VBox(10, statusLbl, buttonBox)

  def startTask = {
    val backgroundThread = new Thread {
      setDaemon(true)
      override def run = {
        runTask
      }
    }
    backgroundThread.start()
  }

  def runTask = {
    for(i <- 1 to 10) {
      try {
        val status =  "Processing " + i + " of " + 10
        Platform.runLater(() => {
          statusLbl.text = status
        })
        println(status)
        Thread.sleep(1000)
      } catch {
        case e: InterruptedException => e.printStackTrace()
      }
    }
  }

  stage = new PrimaryStage {
    title = "Blocking"
    scene = new Scene {
      root = vBox
    }
  }
}

当&#34;开始&#34;按下按钮,状态标签应更新10次,但不是。在控制台中,您可以看到后台线程实际上正在更新状态,但这些不会反映在UI中。为什么呢?

1 个答案:

答案 0 :(得分:2)

问题在于Platform.runLater的调用。要使其工作,请将其更改为:

Platform.runLater {
  statusLbl.text = status
}

runLater[R](op: => R)将代码块作为参数,返回类型为R的值。您正在传递定义匿名函数的代码块。 runLater正在创建一个函数,而不是执行它。