The CS109UI module

The CS109UI module

I have written a simple module called CS109UI that makes it
possible to write programs with a simple graphical user interface
without learning about the Swing library or worrying about event-based
programming. We use this module for several projects in
CS109.

The script starts, prints the version message of cs109ui, and
then opens a new window like this:

Note that your script has not yet terminated, even though the main
function has already returned. To end the script, you have to close
the window manually using the mouse.

Updating the display

You can change the contents of the window by drawing a new image and
calling show again. (You can draw to the same image as before
or use a new one.)

By waiting some time in between changes to the window, you can perform
some simple animation, like letting objects blink or move inside the
window.

Here is a simple example that shows a blinking square. First the
square appears for one second in red, then for one second in blue.
Five seconds later the program terminates automatically
(uitest2.scala):

Keyboard input

If we want to get a bit more advanced, we can perform all interaction
with the user through the window. We can use the drawString
function to show text in our window. The next step is to allow the
user to control the program by pressing keys in the window.

This is done using the waitKey function. It waits until the
user has pressed a key, and then returns the character pressed.
Here is a simple test program
(uitest3.scala):

After the window has appeared, try to type keys with the focus on the
window. You should see the message Got character on your
terminal. Pressing the 'q' key will terminate the program.

Dialogs

We can make our programs more professional by using additional pop-up
windows, usually called "dialogs".

The simplest one just shows a message to the user. The user has to
press "Ok" to continue the program. For instance, with this code

showMessage("This is a message")

we would get this pop-up window:

Slightly more interesting, we can ask a Yes/No-question, and the user
can decide by pressing one of the two buttons:

val yesno: Boolean = askYesNo("Do you like this?")

It looks like this:

The askYesNo function returns the user's choice as a Boolean
value.

Finally, we can ask the user to enter a string:

val name: String = inputString("What is your name?")

It looks like this:

and again the function returns the string entered by the user. (If the
user presses "Cancel" or closes the popup-window, the empty string
is returned.)

Advanced possibilities

There are a few more possibilities in the module: receiving mouse
button clicks from the window, two more dialogs, and setting a
time-out on user input. I will document these when they are
needed for projects, but you can always look at the example
code.