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 "+" => plus
- case "-" => minus
- case "*" => times
- case "/" => divide
- }
- }
- def getXY(a : TextField, b : TextField) : Tuple2[Double, Double] = {
- val x = a.text.replace(',', '.').toDouble
- val y = b.text.replace(',', '.').toDouble
- new Tuple2(x, y)
- }
- def setValuesToButtons(result : Double) {
- a.text = result+""
- b.text = "0"
- info.text = INFO_FIELD_TEXT_DEFAULT
- }
- def plus {
- val xy = getXY(a, b)
- setValuesToButtons(xy._1 + xy._2)
- }
- def minus {
- val xy = getXY(a, b)
- setValuesToButtons(xy._1-xy._2)
- }
- def times {
- val xy = getXY(a, b)
- setValuesToButtons(xy._1*xy._2)
- }
- def divide {
- val xy = getXY(a, b)
- if (xy._2 != 0) {
- setValuesToButtons(xy._1/xy._2)
- } else {
- info.text = "Division by zero"
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement