Drawing Techniques
Now that we’ve learned about the basic tools, let’s put a few of them together. In this section, we’ll look at some techniques for doing fast and flicker-free drawing and painting. If you’re interested in animation, this is for you. Drawing operations take time, and time spent drawing leads to delays and imperfect results. Our goals are 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 do this, we use two techniques: clipping and double buffering. Fortunately, Swing now handles double buffering by default. You won’t have to implement this logic on your own, but it’s useful to understand it.
Our first example, DragImage,
illustrates some of the issues in 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 that image we can drag around on top of
it, as shown in Figure 20-4:
importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassDragImageextendsJComponentimplementsMouseMotionListener{staticintimageWidth=60,imageHeight=60;intgrid=10;intimageX,imageY;Imageimage;publicDragImage(Imagei){image=i;addMouseMotionListener(this);}publicvoidmouseDragged(MouseEvente){imageX=e.getX();imageY=e.getY();repaint();}publicvoidmouseMoved(MouseEvente){}publicvoidpaint(Graphicsg){Graphics2D ...