Advertisement
Guest User

Untitled

a guest
Apr 11th, 2014
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.65 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 "+" => calculate((x, y) => x+y)
  35.       case "-" => calculate((x, y) => x-y)
  36.       case "*" => calculate((x, y) => x*y)
  37.       case "/" => calculate(divide)
  38.     }
  39.   }
  40.  
  41.   def calculate(operation : (Double, Double) => Double) {
  42.     try {
  43.       val x = a.text.replace(',', '.').toDouble
  44.       val y = b.text.replace(',', '.').toDouble
  45.    
  46.       a.text = (operation(x, y)).toString
  47.       b.text = "0"
  48.       info.text = INFO_FIELD_TEXT_DEFAULT
  49.     } catch {
  50.       case e : Exception => info.text = e.getMessage()
  51.     }
  52.   }
  53.  
  54.   def divide (x : Double, y : Double) : Double = {
  55.     if (y == 0) // Otherwise there's going to be NaN instead (why?!)
  56.       throw new ArithmeticException("Division by zero")
  57.     else
  58.       x/y
  59.   }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement