Producing Image Data
There are two
different
approaches to generating image data. The easiest way 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 of the image data yourself. This is
harder, but it can be useful in specific cases: loading and saving
images in files or mathematically analyzing image data are two
examples.
Drawing Animations
Let’s begin with the simpler approach, rendering on an image. 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, but 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 have 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 18.2; here is its source code:
//file: Hypnosis.java import java.awt.*; import java.awt.event.*; import java.awt.geom.GeneralPath; import ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access