【发布时间】:2011-06-04 16:04:23
【问题描述】:
我正在用 scala 编写一个小应用程序。应用程序处理简单的日志文件。因为处理需要一些时间,所以我决定让我的应用程序核心扩展 Actor。
class Application extends Actor {
def react() {
loop {
react {
case Process(file) => // do something interesting with file...
}
}
}
}
通过单击 gui 中的按钮触发日志文件的处理。 gui 使用 scala swing。
object Gui extends SimpleSwingApplication {
val application = new Application().start()
def top = new MainFrame {
val startButton = new Button
reactions += {
case ButtonClicked(`startButton`) => application ! Process(file)
}
}
}
现在,应用程序核心需要通知 gui 当前进度。
sender ! Progress(value) // whenever progress is made
我通过在 gui 中创建一个单独的演员解决了这个问题。 Actor 在 edt 线程中执行。它侦听来自应用程序核心的消息并更新 gui。
object Gui extends SimpleSwingApplication {
val actor = new Actor {
override val scheduler = new SchedulerAdapter {
def execute(fun: => Unit) { Swing.onEDT(fun) }
}
start()
def act() {
loop {
react {
case ForwardToApplication(message) => application ! message
case Progress(value) => progressBar.value = value
}
}
}
}
}
由于应用程序核心需要知道消息的发送者,我也使用这个actor将消息从gui转发到应用程序核心,使我的actor成为新的发送者。
reactions += {
case ButtonClicked(`startButton`) => actor ! ForwardToApplication(Process(file))
}
这段代码工作得很好。我的问题:有没有更简单的方法来做到这一点?对我的应用程序消息简单地使用反应机制会很好:
reactions += {
case Progress(value) => progressBar.value = value
}
任何想法如何实现这一目标?
【问题讨论】: