Advertisement
Guest User

Untitled

a guest
Apr 11th, 2014
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.78 KB | None | 0 0
  1. package week5
  2.  
  3. import swing._
  4. import javax.swing._
  5. import java.awt.BorderLayout
  6. import scala.swing.event._
  7.  
  8. object Calculator extends SimpleSwingApplication {
  9.   final val INFO_FIELD_TEXT_DEFAULT = "------------------------------"
  10.   def numberField = new TextField {
  11.     text = "0"
  12.     columns = 5
  13.   }
  14.  
  15.   val a = numberField
  16.   val b = numberField
  17.   val plusButton = new Button("+")
  18.   val minusButton = new Button("-")
  19.   val timesButton = new Button("*")
  20.   val divisionButton = new Button("/")
  21.   val info = new TextField(INFO_FIELD_TEXT_DEFAULT)
  22.  
  23.   def top = new MainFrame {
  24.     title = "Kuljulator"
  25.     contents = new FlowPanel(
  26.         new FlowPanel(a, b),
  27.         new FlowPanel(plusButton, minusButton, timesButton, divisionButton),
  28.         new FlowPanel(info))
  29.   }
  30.  
  31.   listenTo(plusButton, minusButton, timesButton, divisionButton)
  32.   reactions += {
  33.     case ButtonClicked(x) => x.text match {
  34.       case "+" => plus
  35.       case "-" => minus
  36.       case "*" => times
  37.       case "/" => divide
  38.     }
  39.   }
  40.  
  41.   def getXY(a : TextField, b : TextField) : Tuple2[Double, Double] = {
  42.     val x = a.text.replace(',', '.').toDouble
  43.     val y = b.text.replace(',', '.').toDouble
  44.    
  45.     new Tuple2(x, y)
  46.   }
  47.  
  48.   def setValuesToButtons(result : Double) {
  49.     a.text = result+""
  50.     b.text = "0"
  51.     info.text = INFO_FIELD_TEXT_DEFAULT
  52.   }
  53.  
  54.   def plus {
  55.     val xy = getXY(a, b)  
  56.     setValuesToButtons(xy._1 + xy._2)
  57.   }
  58.  
  59.   def minus {
  60.     val xy = getXY(a, b)
  61.     setValuesToButtons(xy._1-xy._2)
  62.   }
  63.  
  64.   def times {
  65.     val xy = getXY(a, b)
  66.     setValuesToButtons(xy._1*xy._2)
  67.   }
  68.  
  69.   def divide {
  70.     val xy = getXY(a, b)
  71.     if (xy._2 != 0) {
  72.       setValuesToButtons(xy._1/xy._2)
  73.     } else {
  74.       info.text = "Division by zero"
  75.     }
  76.   }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement