scala actor swing代码实践

来源:互联网 发布:矩阵分配律 编辑:程序博客网 时间:2024/05/01 08:10


     

        


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

package com.dt.scala.helloimport scala.swing._import scala.actors.Actorimport 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.helloimport scala.swing._import scala.swing.event._import scala.actors._import scala.actors.Actorimport 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"                }            }        }    }}


版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0