3.2. Shapes and Paths

As you saw in Chapter 2, the Graphics2D class is the rendering engine for the Java 2D API. Two of its basic operations are filling shapes and drawing their outlines. But Graphics2D doesn't know much about geometry, as the song says. In fact, Graphics2D only knows how to draw one thing: a java.awt.Shape. The Shape interface represents a geometric shape, something that has an outline and an interior. With Graphics2D, you can draw the border of the shape using draw(), and you can fill the inside of a shape using fill().

The java.awt.geom package is a toolbox of useful classes that implement the Shape interface. There are classes that represent ellipses, arcs, rectangles, and lines. First, I'll talk about the Shape interface, and then briefly discuss the java.awt.geom package.

Sidebar 2. If You're an Old Dog

You probably remember that the Graphics class had methods for drawing and filling simple shapes: drawRect(), drawOval(), drawArc(), fillRect(), fillOval(), fillArc(), etc. Because Graphics2D is a subclass of Graphics, you can still call these methods to render shapes. In some cases, it's easier to call one of these methods, because you can render a shape in a single step.

On the other hand, these methods use only integer coordinates, and they don't allow you to reuse shapes. Furthermore, the most complex shape that Graphics supports is a polygon defined with straight line segments. The Shape interface also supports curved line segments and multiple sub-shapes, ...

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.