RosettaCodeData/Task/GUI-component-interaction/Scala/gui-component-interaction.scala

46 lines
1.7 KiB
Scala
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import scala.swing._
import scala.swing.Swing._
import scala.swing.event._
object Interact extends SimpleSwingApplication {
def top = new MainFrame {
title = "Rosetta Code >>> Task: component interaction | Language: Scala"
2013-10-27 22:24:23 +00:00
val numberField = new TextField {
text = "0" // start at 0
horizontalAlignment = Alignment.Right
}
2013-04-10 21:29:02 -07:00
2013-10-27 22:24:23 +00:00
val incButton = new Button { text = "Increment" }
2013-04-10 21:29:02 -07:00
val randButton = new Button { text = "Random" }
// arrange buttons in a grid with 1 row, 2 columns
val buttonPanel = new GridPanel(1, 2) {
contents ++= List(incButton, randButton)
}
// arrange text field and button panel in a grid with 2 row, 1 column
2013-10-27 22:24:23 +00:00
contents = new GridPanel(2, 1) { contents ++= List(numberField, buttonPanel) }
2013-04-10 21:29:02 -07:00
// listen for keys pressed in numberField and button clicks
listenTo(numberField.keys, incButton, randButton)
reactions += {
2013-10-27 22:24:23 +00:00
case kt: KeyTyped if (!kt.char.isDigit) => // if the entered char isn't a digit …
kt.consume // … eat the event (i.e. stop it from being processed)
2013-04-10 21:29:02 -07:00
case ButtonClicked(`incButton`) =>
2013-10-27 22:24:23 +00:00
if (numberField.text.isEmpty) numberField.text = "0"
2013-04-10 21:29:02 -07:00
// we use BigInt to avoid long overflow/number format exception
2013-10-27 22:24:23 +00:00
numberField.text = (BigInt(numberField.text) + 1).toString
2013-04-10 21:29:02 -07:00
case ButtonClicked(`randButton`) =>
import Dialog._
2013-10-27 22:24:23 +00:00
numberField.text = showOptions(buttonPanel, message = "Are you sure?",
title = "Choose an option!", entries = List("Yes", "No", "Cancel"),
initial = 2) match {
2014-01-17 05:32:22 +00:00
case Result.Yes => (Long.MaxValue * math.random).toLong.toString
2013-10-27 22:24:23 +00:00
case _ => numberField.text
}
2013-04-10 21:29:02 -07:00
}
2013-10-27 22:24:23 +00:00
centerOnScreen()
2013-04-10 21:29:02 -07:00
}
}