I wrote a Scala program that I would like to run using the user interface (also in Swing). The problem is that when I run it, the user interface freezes until the background program completes. I thought the only way around this would be to run the program in another thread / actor and update the user interface as needed. The update will include a status bar, which will display the file that is currently being processed, and a progress panel.
Since Scala actors are outdated, it's hard for me to plow through Akka to get some basic multithreading. The examples on the Akka website are also quite complex.
But more than that, it's hard for me to wrap my head around how to try to solve this problem. I can come up with the following:
- The background program works like a single actor
- The user interface is the main program
- There is another actor who tells the user interface to update something
Step 3 is what scares me. How to tell the user interface without closing any variable somewhere?
In addition, I am sure that this problem has been resolved earlier. Any sample code for it would be greatly appreciated.
=========================
EDIT: What worked for me
Instead of using Actors, I used futures similar to what pagoda_5b explained in his answer:
Move the status bar and progress bar out def topand make them global variables:
object MyGUIProject extends SimpleSwingApplication {
val txtStatus = new Label
val progressBar = new ProgressBar
def top = new MainFrame {
...
}
}
Calling the background process in the future when I click the button:
val btnStart = new Button {
text = "Click me to start"
reactions += {
case ButtonClicked(_) => {
val myFuture = future {
doLongBackgroundProcess(someString)
}
myFuture onSuccess {
case _ => Swing.onEDT {
txtStatus.text = "Done"
}
}
}
}
}
future Swing.onEDT:
def updateStatus(txt: String) = {
val fut = future {
Swing.onEDT {
txtStatus.text = txt
}
}
}
def doLongBackgroundProcess(str:String) = {
val taskList = getTasks(str)
taskList foreach {x=>
updateStatus("Currently doing task: " + x)
}
}