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, ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.