O'Reilly logo

Java 2D Graphics by Jonathan Knudsen

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

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

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