Java Reference
In-Depth Information
You should see the Applet Viewer window displaying the applet as in
Figure 17-18
.
The arrangement of the buttons is now right-justified in the flow layout. You have the button labels al-
ternating between the two fonts that you created. The buttons also look more like buttons with a beveled
edge.
How It Works
As you saw in Chapter 1, an applet is executed rather differently from a Java program, and it is not really
an independent program at all. The browser (or
appletviewer
in this case) initiates and controls the exe-
cution of the applet. An applet does not require a
main()
method. To execute the applet, the browser first
creates an instance of our applet class,
TryApplet
and then calls the
init()
method for it. This meth-
od is inherited from the
Applet
class (the base for
JApplet
) and you typically override this method to
start the applet on the event dispatch thread. To do this you use the
invokeAndWait()
method from the
SwingUtilities
class to start a
Runnable
thread where the
run()
method calls
createAppletGUI()
for the
JApplet
object that is created by the browser to create the GUI for the applet.
It is not strictly necessary to use
invokeAndWait()
in this example; you could use
invokeLater()
.
There is a significant difference between the methods. The
invokeLater()
method executes the
run()
method asynchronously and allows it to be called after all pending events on the dispatch thread have
been processed. It allows
run()
to return even though there may be dispatch thread events still outstand-
ing. The
invokeAndWait()
method executes the
run()
method synchronously and prevents
run()
from
returning until there are no events outstanding on the event dispatch thread. Thus you should use
in-
vokeAndWait()
for an applet when the initialization code involves handling dispatch thread events. This
is not the case here but applets can often involve dealing with events during the initialization phase, par-
ticularly when image files have to be loaded.
In the
createAppletGUI()
method you set the layout manager for the applet's content pane to be a flow
layout. Before creating the buttons, you create a
BevelBorder
object that you use to specify the border
for each button. To add the buttons, you use the
add()
method for the
JApplet
object. This method adds
a component to the content pane for the applet. In the loop that adds the buttons, you select one or other
of the
Font
objects you have created, depending on whether the loop index is even or odd and then set
edge
as the border by calling the
setBorder()
member. This would be the same for any component.