Java Reference
In-Depth Information
As a general rule, an AWT-based applet writes to its window only when its
paint( )
method
is called by the run-time system. This raises an interesting question: How can the applet
itself cause its window to be updated when its information changes? For example, if an
applet is displaying a moving banner, what mechanism does the applet use to update the
window each time this banner scrolls? Remember that one of the fundamental architectural
constraints imposed on an applet is that it must quickly return control to the Java run-time
system. It cannot create a loop inside
paint( )
that repeatedly scrolls the banner, for ex-
ample. This would prevent control from passing back to the run-time system. Given this
constraint, it may seem that output to your applet's window will be difficult at best. For-
tunately, this is not the case. Whenever your applet needs to update the information dis-
played in its window, it simply calls
repaint( )
.
The
repaint( )
method is defined by the AWT's
Component
class. It causes the run-time
system to execute a call to your applet's
paint( )
method. Thus, for another part of your
applet to output to its window, simply store the output and then call
repaint( )
. This causes
a call to
paint( )
, which can display the stored information. For example, if part of your
applet needs to output a string, it can store this string in a
String
variable and then call
re-
paint( )
. Inside
paint( )
, you will output the string using
drawString( )
.
The simplest version of
repaint( )
is shown here:
void repaint( )
This version causes the entire window to be repainted.
Another version of
repaint( )
specifies a region that will be repainted:
void repaint(int
left
, int
top
, int
width
, int
height
)
Ask the Expert
Q
:
Is it possible for a method other than
paint( )
or
update( )
to output to an applet's
window?
A
:
Yes. To do so, you must obtain a graphics context by calling
getGraphics( )
(defined
by
Component
) and then use this context to output to the window. However, for
most AWT-based applications, it is better and easier to route window output through
paint( )
and to call
repaint( )
when the contents of the window change.