4.1. Painting
Filling the interior of a shape is a two-step process:
First, tell the Graphics2D how to fill shapes with a call to setPaint(). This method accepts any object that implements the java.awt.Paint interface. The Graphics2D stores the Paint away as part of its state. When it comes time to fill a shape, Graphics2D will use the Paint to determine what colors should be used to fill the shape. The 2D API comes with three kinds of "canned" paints: solid colors, a linear color gradient, and a texture fill. You can add your own Paint implementations if you wish.
Now you can tell Graphics2D to fill a shape by passing it to fill().
Paints are immutable, which means they can't be modified after they are created. The reason for this is to avoid funky behavior when rendering. Imagine, for example, if you wanted to fill a series of shapes with a solid color. First, you'd call setPaint() on the Graphics2D; then you would paint the shapes using fill(). But what if another part of your program changed the Paint that Graphics2D was using? The results might be quite bizarre. For this reason, objects that implement Paint should not allow themselves to be changed after they are created.
Figure 4.2 shows the three types of painting supported by the 2D API. The figure contains three shapes:
The ellipse is filled with a solid color.
The rounded rectangle is filled with a color gradient.
The arc is filled with a texture, built from van Gogh's Starry Night.
Figure 4.2. Three shapes and three ...
Get Java 2D Graphics 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.