Java Reference
In-Depth Information
The RoundButton shows all of the principles I discuss in the previous section, and it
uses double buffering to an offscreen Image instance to prevent the possibility of flicker-
ing when the component repaints. It's not a complex component, but it is a little long, so
let's take it field by field and method by method.
The RoundButton has a label field that contains the string labeling the button for
the user. It must also track its state, whether it's pressed or not, which it does using
the protected pressed field. It maintains an Image for offscreen drawing, aptly named
offscreen , and two private constant variables: the preferred size of the button and the
default padding for the button label.
Tip You may be wondering why I chose protected for the access protection level of these fields. I'm
assuming that this class will be part of a more sophisticated GUI framework, and thus might have subclasses
that customize the behavior of this button and need access to its fields.
The RoundButton constructor simply caches aside the label you provide and enables
mouse events for the component. The RoundButton must override the invalidate method
as part of the double buffering. The windowing environment calls invalidate as part of the
component's sizing and layout, which in turn requires the RoundButton to allocate a new
offscreen bitmap for drawing. For speed, the invalidate method only invalidates the cur-
rent offscreen bitmap; it leaves allocating the new offscreen bitmap to the paint method.
The update method—invoked by the windowing toolkit hierarchy as a result of a sys-
tem redraw—must, by definition, clear the component's background and completely
redraw the component. Because paint draws the entire component to an offscreen
bitmap and then copies that bitmap to the screen, update can simply call paint directly.
The paint method does the real work for the RoundButton . It begins by creating the
offscreen bitmap if one is required, and then it obtains a Graphics instance for the off-
screen bitmap. It then draws the button on the offscreen bitmap from back to front, with
the following operations:
1. It computes the button background, which is slightly darker if the button is
being pressed.
2. It draws a filled circle for the button using the color it computed in the
previous step.
3. Once it has drawn the background, it draws the border using a shade darker
than the button's background.
4. With the background and border drawn, it draws the button's label, which is
centered in the region defined by the button.
 
Search WWH ::




Custom Search