GUI 初体验与事件处理实战

参考文献
scala 深入浅出实战经典 . 王家林

官网swing组件单独成jar说明:  http://www.scala-lang.org/news/2.11.0/

scala.swing包下载地址:http://repo1.maven.org/maven2/org/scala-lang/modules/scala-swing_2.11/1.0.2/

场景
使用scala GUI编写基本的事件处理程序
实验

【Mr.Snail注】看王老师解说scala GUI后,自己编码的时候发现 scala.swing._组件包无法导入。原来scala2.11.0后,scala.swing包单独做成了jar包-具体下载地址参加"参考文献"

package com.scode.scala
/**
 * author: Ivy Peng
 * function: GUI 编程初体验 之 监听用户的按钮点击次数 与 读取并输出本地文件路径 实战
 * date:2016/03/30 10.19
 * sum:
 * 1、封装java GUI,提供更友好的操作接口-有待后续体会
 * 2、Application -> Frame -> Panel -> 各种组件(button、label);各种组件是并行的关系
 */
import scala.swing._
import scala.swing.event.ButtonClicked

object GUI_Panel_Layout extends SimpleSwingApplication
{
  def top = new MainFrame
  {
    title = "Hello Scala"
    
    val button = new Button
    {
      text = "my scala, your way "
    }
    val label = new Label
    {
      text = "Spark"
    }
    
    //Orientation 标识组的位置关系 
    //eg、Horizontal表示水平:label的位置与button在同一水平行,具体参见程序执行结果
    contents = new BoxPanel(Orientation.Horizontal)
    {
      contents += button
      contents += label
      border = Swing.EmptyBorder(30,30,30,30)
    }
    listenTo(button)
    var clicks = 0
    reactions +=
    {
      case ButtonClicked(button) =>
      {
         clicks += 1
         label.text = "Clicked "+clicks +" times"
      }
    }
  }
}

执行结果
GUI 初体验与事件处理实战_第1张图片
/**
 *  读取并输出本地文件路径
 */
object GUI_Event extends SimpleSwingApplication
{
  val fileChooser = new FileChooser(new File("."))
  fileChooser.title = "My File"
  val button = new Button
  {
    text = "please choose a File from local:"
  }
  val label = new Label
  {
    text = "No file selected yet "
  }
  val mainPanel = new FlowPanel
  {
    contents+=button
    contents+=label
  }
  
  def top = new MainFrame
  {
    title="Scala GUI Programming advanced"
    contents = mainPanel
    
    listenTo(button)
    reactions+=
    {
        case ButtonClicked(button) =>
        {
          val result = fileChooser.showOpenDialog(mainPanel)
          if(result == FileChooser.Result.Approve)
          {
            label.text = fileChooser.selectedFile.getPath
          }
        }
    }
  }
}
执行结果

选中文件后:



你可能感兴趣的:(GUI 初体验与事件处理实战)