O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Custom Paint

Figure 12-8 showed a variety of shape-filling techniques; it included a large letter A filled with a complex pattern defined by the GenericPaint class. Example 12-18 shows the implementation of this class. You may want to take another look at Example 12-10 to see how the GenericPaint class is used, before you dive into the code listed here.

The GenericPaint class itself is pretty simple: it defines both the abstract color computation methods that subclasses implement and a createContext( ) method that returns a PaintContext. The implementation of PaintContext does all the hard work. This is pretty low-level stuff, so don’t be dismayed if you don’t understand everything. The code should at least give you a basic idea of how painting works in Java 2D.

Example 12-18. GenericPaint.java

package je3.graphics; import java.awt.*; import java.awt.geom.*; import java.awt.image.*; /** * This is an abstract Paint implementation that computes the color of each * point to be painted by passing the coordinates of the point to the calling * abstract methods computeRed( ), computeGreen( ), computeBlue( ) and * computeAlpha( ). Subclasses must implement these three methods to perform * whatever type of painting is desired. Note that while this class provides * great flexibility, it is not very efficient. **/ public abstract class GenericPaint implements Paint { /** This is the main Paint method; all it does is return a PaintContext */ public PaintContext createContext(ColorModel cm, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required