Let's try our first program, gui1.scala:
import scala.swing._ class UI extends MainFrame { title = "GUI Program #1" preferredSize = new Dimension(320, 240) contents = new Label("Here is the contents!") } object GuiProgramOne { def main(args: Array[String]) { val ui = new UI ui.visible = true println("End of main function") } }When you compile and run the program like this:
> fsc gui1.scala > scala GuiProgramOne End of main functionyou should see a window appearing like this:
If you look carefully, you will see that the output "End of main function" appears in the terminal, but the program does not stop. Even though the main method of GuiProgramOne returns, the program keeps running — the Swing library takes care of that.
We have not set up any responses to events in this program, but some actions already work fine: For instance, you can move and resize the window, you can iconify it or maximize it. The contents is nicely moved to appear in the center. Finally, when you press the X symbol in the title bar, the window closes—and the program terminates! All these events are handled by the Swing library itself, so we do not have to worry about them.
Let's have a look at the UI (for UserInterface) class. This class extends the Swing class scala.swing.MainFrame, which is a window that can appear on the screen. This means that a UI object has all the methods and fields of the MainFrame class in addition to its own methods and fields, and can be used like a MainFrame.
In this small program, the UI constructor only sets three of its fields (which it has "inherited" from the MainFrame class), namely title (which is the title that appears on top of the window), the preferred size (which is the starting size of the window), and its contents. The contents is what will appear inside the window, and it has to be a component, that is, an object of a class that extends scala.swing.Component. There are many such component classes. Here we use a very simple one, scala.swing.Label, which only displays a string.