Producing Image Data
There are two approaches to generating image data. The high-level
method is to treat the image as a drawing surface and use the methods of
Graphics2D to render things into the
image. The second way is to twiddle the bits that represent the pixels of
the image data yourself. This is harder, but gives you arbitrary control
for handling specific formats or mathematically analyzing or creating
image data.
Drawing Animations
Let’s begin with the simpler approach, rendering an image through drawing. We’ll throw in a twist to make things interesting: we’ll build an animation. Each frame will be rendered as we go along. This is very similar to the double buffering we examined in the last chapter, except that this time we’ll use a timer instead of mouse events as the signal to generate new frames.
Swing performs double buffering automatically, so we don’t even need to worry about the animation flickering. Although it looks like we’re drawing directly to the screen, we’re really drawing into an image that Swing uses for double buffering. All we need to do is draw the right thing at the right time.
Let’s look at an example, Hypnosis, that illustrates the technique. This
example shows a constantly shifting shape that bounces around the inside
of a component. When screen savers first came of age, this kind of thing
was pretty hot stuff. Hypnosis is
shown in Figure 21-2.

Figure 21-2. A ...