Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package week5
- import swing._
- import javax.swing._
- import java.awt.BorderLayout
- import scala.swing.event._
- object Calculator extends SimpleSwingApplication {
- final val INFO_FIELD_TEXT_DEFAULT = "------------------------------"
- def numberField = new TextField {
- text = "0"
- columns = 5
- }
- val a = numberField
- val b = numberField
- val plusButton = new Button("+")
- val minusButton = new Button("-")
- val timesButton = new Button("*")
- val divisionButton = new Button("/")
- val info = new TextField(INFO_FIELD_TEXT_DEFAULT)
- def top = new MainFrame {
- title = "Kuljulator"
- contents = new FlowPanel(
- new FlowPanel(a, b),
- new FlowPanel(plusButton, minusButton, timesButton, divisionButton),
- new FlowPanel(info))
- }
- listenTo(plusButton, minusButton, timesButton, divisionButton)
- reactions += {
- case ButtonClicked(x) => x.text match {
- case "+" => calculate((x, y) => x+y)
- case "-" => calculate((x, y) => x-y)
- case "*" => calculate((x, y) => x*y)
- case "/" => calculate(divide)
- }
- }
- def calculate(operation : (Double, Double) => Double) {
- try {
- val x = a.text.replace(',', '.').toDouble
- val y = b.text.replace(',', '.').toDouble
- a.text = (operation(x, y)).toString
- b.text = "0"
- info.text = INFO_FIELD_TEXT_DEFAULT
- } catch {
- case e : Exception => info.text = e.getMessage()
- }
- }
- def divide (x : Double, y : Double) : Double = {
- if (y == 0) // Otherwise there's going to be NaN instead (why?!)
- throw new ArithmeticException("Division by zero")
- else
- x/y
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement