flying3615
2/3/2017 - 8:33 AM

simple scala gui app

simple scala gui app

package gui

import scala.swing.{Label, _}
import scala.swing.event.EditDone

/**
  * Created by Administrator on 2017/2/3.
  */
class TempConverter  extends MainFrame {

  title = "Celsius/Fahrenheit Converter"

  object celsius extends TextField {columns = 5}
  object fahrenheit extends TextField {columns = 5}

  val f_done =  new Label("fahrenheit done")
  val c_done = new Label("celsius done")

  contents = new FlowPanel {
    contents += celsius
    contents += new Label(" Celsius = ")
    contents += fahrenheit
    contents += new Label(" Fahrenheit")
    contents +=  Button("Show Me"){ pressMe() }
    border = Swing.EmptyBorder(30,10,10,10)

    listenTo(celsius,fahrenheit)

    reactions += {
      case EditDone(`fahrenheit`) =>
        exceptWrapp(()=>{
          val f =  fahrenheit.text.toInt
          val c = (f-32)*5/9
          celsius.text = c.toString
          contents -= c_done
          contents += f_done
          revalidate()  // refresh layout
          repaint()
        },fahrenheit)

      case EditDone(`celsius`) =>
        exceptWrapp(()=>{
        val c = celsius.text.toInt
        val f = c*9/5 + 32
        fahrenheit.text = f.toString
        contents -= f_done
        contents += c_done
        revalidate()  // refresh layout
        repaint()
        },celsius)
    }
  }

  def exceptWrapp(f:()=>Unit, textField: TextField) {
    try{
      f()
    }catch {
      case e:NumberFormatException=>Dialog.showMessage(contents.head, "NumberFormatException!", title="ERROR!")
    }finally {
      //set default value to 0
      textField.text = 0.toString
    }
  }

  def pressMe() {
    Dialog.showMessage(contents.head, "Thank you!", title="You pressed me")
  }

}

object Main extends App{
  val tempConverter = new TempConverter
  tempConverter.visible = true
}