Using Drawing Techniques
Having learned to walk, let’s try a jog. In this section, we’ll look at some techniques for doing fast and flicker-free drawing and painting. If you’re interested in animation or smooth updating, this is for you.
Drawing operations take time, and time spent drawing leads to delays and imperfect results. Our goal is to minimize the amount of drawing work we do and, as much as possible, to do that work away from the eyes of the user. To see how to eliminate flicker and blinking problems, we’ll look at an application that animates very badly. The good news is that Swing automatically solves a lot of flicker problems.
TerribleFlicker
illustrates some of the problems of updating a display. Like many
animations, it has two parts: a constant background and a changing
object in the foreground. In this case, the background is a
checkerboard pattern and the object is a small, scaled image we can
drag around on top of it, as shown in Figure 17.4. Our first version of
TerribleFlicker lives up to its name, doing a very
poor job of updating.

Figure 17-4. The TerribleFlicker application
//file: TerribleFlicker.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TerribleFlicker extends JComponent implements MouseMotionListener { int grid = 10; int imageX, imageY; Image image; int imageWidth = 60, imageHeight = 60; public TerribleFlicker(Image ...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