Skip to content

Instantly share code, notes, and snippets.

@timmolderez
Last active November 22, 2017 14:21
Show Gist options
  • Save timmolderez/2e53d2b99421888c663a56647fa7d667 to your computer and use it in GitHub Desktop.
Save timmolderez/2e53d2b99421888c663a56647fa7d667 to your computer and use it in GitHub Desktop.
Design patterns exercise (command)
import java.awt.Dimension
import scala.swing.BorderPanel.Position
import scala.swing.event.ButtonClicked
import scala.swing.{BorderPanel, Button, GridPanel, MainFrame, TextField}
object Calculator {
def main(args: Array[String]): Unit = {
val frame = new MainFrame() {
title = "Calculator"
preferredSize = new Dimension(320, 240)
contents = new Calculator
}
frame.visible = true
}
}
class Calculator() extends BorderPanel {
private val display = new TextField("0")
private var result: Double = 0
private var operator = "="
private var calculating = true
display.editable = false
layout(display) = Position.North
val panel = new GridPanel(4, 4) {
val buttonLabels = "789/456*123-0.=+"
var i = 0
while (i < buttonLabels.length) {
val b = new Button(buttonLabels.substring(i, i + 1))
contents += b
listenTo(b)
reactions += {
case ButtonClicked(`b`) =>
buttonClicked(b.text)
}
i += 1
}
}
layout(panel) = Position.Center
private def buttonClicked(cmd: String): Unit = {
if ('0' <= cmd.charAt(0) && cmd.charAt(0) <= '9' || cmd == ".") {
if (calculating)
display.text = cmd
else
display.text = display.text + cmd
calculating = false
} else {
if (calculating) {
if (cmd == "-") {
display.text = cmd
calculating = false
} else
operator = cmd
} else {
val x = display.text.toDouble
calculate(x)
operator = cmd
calculating = true
}
}
}
private def calculate(n: Double): Unit = {
if (operator == "+") result += n
else if (operator == "-") result -= n
else if (operator == "*") result *= n
else if (operator == "/") result /= n
else if (operator == "=") result = n
display.text = "" + result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment