# Java Notes

# GUI Issues

Here are some event-driven programming teaching issues that have come up when I've taught CMIS 340 (Java).

User causes method call. One part of even-driven programming is pretty simple -- the programmer has to tell which function (method) to call when the user does something on the interface. This idea is easy, and I don't think the students have much of a problem with it, except that there are several alternative ways to package the listener method: eg, named inner class listener (simplest), anonymous listener, and the dreaded `this` (the most complex and awkward, but Wu's choice). There are other ways to write listeners, but the previous three seem to be the most common cases.

Scope. It's harder to explain the scope rules so that the listener function can reference the elements it needs. One easy answer is to simply declare all components as instance variables in the outer class, as Wu and NetBeans do. I've tried to declare only the minimum number of components as instance variables and leave the others as local variables. Altho this seems more "correct" to me, it introduces a complexity that perhaps should be avoided. One scope issue comes up using inner class listeners. If you want to refer to the outer class instance (eg, as the first parameter in JOptionPane), you have to qualify `this` with the name of the outer class. [If that last issue didn't make sense to you, just ignore it -- it isn't worth the bother of a big example at the momemnt]

Go to sleep. A hard transition for some is to give up the control of the familiar read-compute-write cycle. It was hard for me. It's difficult to convince these traditional programmers to simply build the interface, then go to sleep and let the user decide which functions should be called.

Is is really asleep? It used to bother me that the main program would build the GUI, then exit. Why didn't this stop the program? It doesn't seem to bother most students tho. For the record, the final JFrame call on `show()` or `setVisible(true)` starts a separate thread to monitor the GUI, so the original thread can terminate without stopping the program. Of course, when I've explained this fascinating thing to students, their eyes glazed over. My suggestion is to ignore it unless asked.