首页 > 代码库 > Scala界面事件处理

Scala界面事件处理


演示样例代码:


import scala.swing.SimpleSwingApplication
import scala.swing.MainFrame
import scala.swing.Button
import scala.swing.Label
import scala.swing.Orientation
import scala.swing.BoxPanel
import scala.swing.Swing
import scala.swing.event.ButtonClicked

object GUI_Panel_Layout 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) //监听该button
    var clicks = 0
    reactions += {
      case ButtonClicked(button) => {
        clicks += 1
        label.text = "Clicked " + clicks + "times"
      }
    }
  }

执行效果(监听button点击次数):

技术分享技术分享



==========================================================

演示样例代码二:

import scala.swing.SimpleSwingApplication
import scala.swing.FileChooser
import java.io.File
import scala.swing.MainFrame
import scala.swing.FlowPanel
import scala.swing.Button
import scala.swing.Label
import scala.swing.event.ButtonClicked


object GUI_Event extends SimpleSwingApplication {
  
  val fileChooser = new FileChooser(new File(".")) //文件对话框
  fileChooser.title = "File Chooser"
  val button = new Button{
    text = "Choose a File from local"
  }
  val label = new Label {
    text = "No any file selected yet."
  }
  val mainPanel = new FlowPanel{
    contents += button
    contents += label
  }
  
  def top = new MainFrame{
    title = "Scala GUI Programing advanced By LEAF !!!"
    contents = mainPanel
    
    listenTo(button)
    
    reactions += {
      case ButtonClicked(b) => {
        val result = fileChooser.showOpenDialog(mainPanel)
        if(result == FileChooser.Result.Approve){
          label.text = fileChooser.selectedFile.getPath()
        }
      }
    }
  }
  
}


执行效果:

技术分享


当点击choose a file from local时。我们能够得到当前文件系统,如图:

技术分享


当我们选择某一个文件时。label中监听该文件的绝对路径(比方我们选择.class文件):

技术分享





相关来源:DT大数据梦工厂,微信公众号是DT_Spark,每天都会有大数据实战视频公布,请您持续学习。

相关资料:

scala深入浅出实战经典完整视频、PPT、代码下载:

百度云盘:http://pan.baidu.com/s/1c0noOt6

腾讯微云:http://url.cn/TnGbdC

360云盘:http://yunpan.cn/cQ4c2UALDjSKy  訪问password45e2





Scala界面事件处理