Java Reference
In-Depth Information
main()
defers GUI creation to the EDT to avoid potential thread-synchronization
problems. Because it's beyond this chapter's scope to discuss these problems, check
out
The Java Tutorial
(
http://download.oracle.com/javase/tutorial/
uiswing/concurrency/dispatch.html
)
and the “Swing threading and the
event-dispatch thread” article (
http://www.javaworld.com/javaworld/
jw-08-2007/jw-08-swingthreading.html
)
formoreinformation.(Although
these sources discuss this topic in a Swing context, other sources also include AWT.
Therefore, you should create AWT-based as well as Swing-based GUIs on the EDT.)
TempVerter()
firstinvokesthe
Frame(String title)
constructorvia
su-
per(“tempverter”);
sothat
TempVerter
willappearontheframewindow'sti-
tlebar. It then registers a window listener with the frame window so that this window
willclose(andtheapplicationwillend)whentheuserclosesthewindow(byclicking
the X button on the window's titlebar, for example).
Thelistenerisaninstanceofa
WindowAdapter
anonymoussubclass,whichover-
rides
WindowListener
's
void windowClosing(WindowEvent we)
and
void windowClosed(WindowEvent we)
methods. Clicking X or selecting
Close from the window's system menu triggers a call to
windowClosing()
. You
wouldtypicallyoverridethismethodtosavechanges(e.g.,atexteditor'sunsavededits).
Toproperlyterminatetheapplication,
windowClosing()
mustinvoke
Window
's
void dispose()
method,whichreleasesallthenativescreenresourcesusedbythe
windowandpostsawindow-closedeventtotheapplication'seventqueue.AWTsubse-
quentlydispatchesthiseventbyinvoking
windowClosed()
tosignifythatthewin-
dow has closed. Any final cleanup can be performed in this method.
Note
Some people prefer to invoke the
java.lang.System
class's
void
exit(int status)
method to terminate the application. For more information,
check out Oracle's “AWT Threading Issues” page at
ht-
Continuing, the constructor instantiates
Panel
to contain the GUI's components. It
thenassignsathree-row-by-two-column
GridLayout
layoutmanagertothiscontain-
er to manage its components.
Eachofthefirsttwogridrowspresents
Label
and
TextField
instances.Thelabel
tellstheuserwhattoenterorindicatesthatthetextfieldisdisplayingaresult.Thetext-
fieldsolicitsinputorpresentsoutput.Thevaluepassedtoeach
TextField
construct-