Custom Shapes

Figure 12-4 showed how Java 2D can be used to draw and fill various types of shapes. One of the shapes shown in that figure is a spiral, which was drawn using the Spiral class, a custom Shape implementation shown in Example 12-15. That example is followed by another custom shape, PolyLine, in Example 12-16. PolyLine represents a series of connect line segments, and is the basis of the ScribblePane class of Example 11-13. PolyLine also features prominently in Chapter 14, where it is used for dragging-and-dropping scribbles.

The Shape interface defines three important methods (some of which have multiple overloaded versions) that all shapes must implement. The contains( ) methods determine whether a shape contains a point or a rectangle; a Shape has to be able to tell its inside from its outside. The intersects( ) methods determine whether any part of the shape intersects a specified rectangle. Since both contains( ) and intersects( ) are difficult to compute exactly for a spiral, the Spiral class approximates the spiral with a circle for the purposes of these methods.

The getPathIterator( ) methods are the heart of any Shape implementation. Each method returns a PathIterator object that describes the outline of the shape in terms of line and curve segments. Java 2D relies on PathIterator objects to draw and fill shapes. The key methods of the SpiralIterator implementation are currentSegment( ), which returns one line segment of the spiral, and next( ), which moves ...

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.