第三十二章 GUI編程
package SecondWithProgrammingInScala
import java.io.File
import scala.swing.{TextField, _}
import scala.swing.event.{ButtonClicked, EditDone}
/**
* GUI 編程
* 大致的使用和實際效果和JavaSwing沒啥區別
* 之前使用過Swing和Vaadin(Java->Html/js) ,相比瀏覽器流派 ,Java客戶端適用性還是低一些的
*
*
* 使用swing時候出現了版本問題
* scala在2.10以後對模塊進行了比較大的劃分 ,不少包被拆分成了不同的模塊
* 使用maven關聯要注意
* 以scala-library爲核心 ,核心版本號2.12去關聯其他模塊包
* 官方還提供了一個scala-lang-all ,包括了之前拆分出去的包
*
*/
object ScalaSwingApp extends SimpleSwingApplication {
/**
* 和Java編寫方式不同 ,Java大多將參數通過構造函數傳遞進去
* Button okBtn = new Button(text = ok)
* scala而多是使用{}直接重載裏面的屬性(實質是匿名子類) ,更符合實際 ,不同功能的按鈕就是不同的類.
* val okBtn = new Button{override text = ok}
* : new OkButton{override text = ok} extends Button
*/
override def top: Frame = new MainFrame {
title = "Scala Swing App"
val clickBtn = new Button {
text = "Click me"
}
val clickBlueBtn = new Button {
background = java.awt.Color.BLUE
text = "Click me"
}
val tipL = new Label {
text = "No button clicks registered"
}
contents = new BoxPanel(Orientation.Vertical) {
contents += clickBtn
contents += clickBlueBtn
contents += tipL
border = Swing.EmptyBorder(30, 30, 10, 30)
}
listenTo(clickBtn, clickBlueBtn)
var nClicks = 0
reactions += {
case ButtonClicked(btn) => {
nClicks += 1
if (btn == clickBlueBtn) tipL.text = "You just Click the Blue Button:" + nClicks
else tipL.text = "Number of button Clicks:" + nClicks
}
}
}
}
/**
* 簡單計算器
*/
object Calculation extends SimpleSwingApplication {
override def top: Frame = new MainFrame {
title = "簡單計算器"
object Elem1 extends TextField {
columns = 5
}
object Elem2 extends TextField {
columns = 5
}
object Func extends TextField {
columns = 2
}
object Result extends TextField {
columns = 20
}
val tips_defualt = "請輸入要計算的值[0-9]和運算符[+-*/]"
val tipsL = new Label(tips_defualt)
contents = new BoxPanel(Orientation.Vertical) {
contents += tipsL
contents += new BoxPanel(Orientation.Horizontal) {
contents += Elem1
contents += new Label(" ")
contents += Func
contents += new Label(" ")
contents += Elem2
}
contents += Result
border = Swing.EmptyBorder(30, 30, 30, 30)
}
var errors = 0
listenTo(Elem1, Elem2, Func)
reactions += {
case EditDone(_) => calculate
}
def calculate: Unit = {
try {
tipsL.text = tips_defualt
Func.text match {
case "+" => Result.text = (Elem1.text.toInt + Elem2.text.toInt).toString
case "-" => Result.text = (Elem1.text.toInt - Elem2.text.toInt).toString
case "*" => Result.text = (Elem1.text.toInt * Elem2.text.toInt).toString
case "/" => Result.text = (Elem1.text.toInt / Elem2.text.toInt).toString
case _ => tipsL.text_=("運算符輸入錯誤 ,請重新輸入")
}
} catch {
case e: NumberFormatException => tipsL.text_=("數值輸出錯誤 ,請重新輸入")
case e => tipsL.text_=(e.getMessage)
}
}
}
}