In our second program, gui2.scala, we learn how to program a response to an event. We will do something unusual, and simply fill the entire window with a button:
import scala.swing._
class UI extends MainFrame {
title = "GUI Program #2"
preferredSize = new Dimension(320, 240)
contents = Button("Press me, please") { println("Thank you") }
}
object GuiProgramTwo {
def main(args: Array[String]) {
val ui = new UI
ui.visible = true
}
}
When we run the program, it looks similar to the previous one, but the
color of the window is different, and when you move the mouse over it
you notice that it is actually a large button:
Note how we set this up:
contents = Button("Press me, please") { println("Thank you") }
The Button function constructs a Button object. It
takes two argument lists. The first argument list contains just the
text that will appear inside the button. The second argument list
contains an action that will occur when the button is pressed.
There is something funny about this second argument list: The
operation println is not executed when the Button
function is called. Instead, the operation is interpreted as a
function object, to be used when the button is pressed.
By the way, we could have written the second argument list with the usual syntax with round parentheses:
contents = Button("Press me, please")(println("Thank you"))
It is customary, however, in this case to write the action in curly
braces as we did above, to make it more clear that this is a function
object that is being stored to be used in the future.