Java Reference
In-Depth Information
fulfill by implementing the Component interface—requires that drawing occur via callbacks
to the component, specifically through its paint method. Your paint method is passed a
Graphics object, which has all of the primitives you require to perform two-dimensional
painting on a canvas.
It's important that you refrain from caching the Graphics object you receive when the
system invokes your paint method, or from painting in methods other than your paint
method. Other methods may be invoked at inappropriate times for your component to
draw, such as when it's not visible or when the Graphics object isn't in a state to perform
drawing. When the framework invokes your paint method, the Graphics object is precon-
figured with the appropriate state for drawing your component, including the following
graphics rendering options:
• The Graphics object's color is set to the component's foreground property.
• The Graphics object's font is set to the component's font property.
• The Graphics object's translation is set such that the origin (0,0) represents the
upper-left corner of the component.
• The Graphics object's clip rectangle is set to the area of the component that needs
to be redrawn.
Of course, you're free to reconfigure the Graphics object passed to your paint method
as necessary.
To signal to the component that it should redraw, the application—or the compo-
nent itself—should invoke one of the component's repaint methods. When invoking
repaint , whenever possible you should include the bounds that must be repainted, so
that the component can limit the redrawing to the region that's necessary. You can also
pass a time interval in milliseconds, indicating that the component should repaint itself
before the specified number of milliseconds elapses. This form of repaint is especially
useful when performing multiple repaints, because it lets you queue up all of the drawing
work at once.
Note that although it looks similar, the update method provided by a component isn't
the same as repaint . Only the AWT event system invokes update in response to an appli-
cation-triggered redraw request; system repaints do not trigger a call to update . This lets
you hook either system-level redraw requests (by overriding update ) or application-level
redraw requests (by overriding repaint ). However, odds are that you will want the default
component behavior for both repaint and update .
Container subclasses, which can contain more than one component, are themselves
Component subclasses and can also perform their own drawing by overriding the paint
method. The default implementation of the Container 's paint method is to invoke paint
on any of its visible children that intersect the rectangle to be painted, so if you're imple-
menting a Container subclass that knows how to paint, it's imperative that your
container's paint method invoke the superclass's paint method, as shown in Listing 9-4.
 
Search WWH ::




Custom Search