您的位置:首页 > 编程语言

scala actor swing代码实践

2015-07-31 18:12 369 查看
     

        

 注意:我一开始用了新的scala ide for eclipse,用的是scala 2.11.7,默认没有swing包。

package com.dt.scala.hello
import scala.swing._
import scala.actors.Actor
import scala.actors.Actor.?
import scala.swing.event.ButtonClicked
/**
* @author arsenal
*/
object GuiScala extends SimpleSwingApplication{
def top = new MainFrame{
calClickCount.start()
title = "study scala gui"
val button = new Button{
text = "click me"
}

val label = new Label()
{
text = "new"
}

contents = new BoxPanel(Orientation.Vertical)
{
contents += button
contents += label
border = Swing.EmptyBorder(50, 50, 50, 50)
}

listenTo(button);
reactions += {
case ButtonClicked(button) =>{
calClickCount ! label
}
}

}

object calClickCount extends Actor
{
def act
{
var clickCount = 0
var text = ""
loop{
react{
case label:Label =>
{

clickCount += 1
text = "click count = " + clickCount
println(text)
label.text = text
}
}
}
}
}

}

这边不能用self.receive来接收统计的次数由主线程来修改text.会报错,感谢群里有同学问起这个错误,我花了点时间想了下,解决了。

这边的重点是receive是 actor的方法,但直接在这里GUI调用self得到的不是actor, 而是UIElement

package com.dt.scala.hello
import scala.swing._
import scala.swing.event._
import scala.actors._
import scala.actors.Actor
import scala.actors.Actor._
import scala.runtime.StringAdd

/**
* @author arsenal
*/
object GuiSelfText  extends SimpleSwingApplication{
def top = new MainFrame {
title = "Second GUI"
val button = new Button {
text = "Scala"
}
val label = new Label {
text = "Here is Spark!!!"
}
contents = new BoxPanel(Orientation.Vertical) {
contents += button
contents += label
border = Swing.EmptyBorder(50,50,50,50)
}

listenTo(button)
var clicks = 0
reactions += {
case ButtonClicked(button) => {
clicks += 1

val hiActor = new HelloActor
hiActor.start

val msg = "Received Message"
val k = actor{
hiActor ! clicks
while(true)
{
receive{
case msg:String => label.text = msg
println(msg)
case _ => {println("1")}
}

}
}

}
}
}
}

class HelloActor extends Actor{
def act(){
while(true){
receive{
case 1 => {
sender ! "Clicked One Times"
}
case 2 => {
sender ! "Clicked Two Times"
}
case _ => {
sender ! "Clicked more than Two Times"
}
}
}
}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: