1

这是代码:

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
    }
  }
}

当按下“开始”按钮时,状态标签应该更新 10 次,但事实并非如此。从控制台您可以看到后台线程实际上正在更新状态,但这些并没有反映在 UI 中。为什么?

4

1 回答 1

2

问题在于调用Platform.runLater. 为了使其工作,将其更改为:

Platform.runLater {
  statusLbl.text = status
}

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

于 2015-09-18T02:25:42.890 回答