3.3. Lines and Curves

The 2D API includes shape classes that represent straight and curved line segments. These classes all implement the Shape interface, so they can be rendered and manipulated like any other Shape. Although you could create a single straight or curved line segment yourself using GeneralPath, it's easier to use these canned shape classes. It's interesting that these classes are Shapes, even though they represent the basic segment types that make up a Shape's path.

3.3.1. Line2D

The java.awt.geom.Line2D class represents a line whose coordinates can be retrieved as doubles. Like Point2D, Line2D is abstract. Subclasses can store coordinates in any way they wish. Figure 3.11 shows the hierarchy.

Figure 3.11. Line2D family of classes

Line2D includes several setLine() methods you can use to set a line's endpoints:

public abstract void setLine(double x1, double x2, double y1, double y2)

This method sets the endpoints of the line to x1, y1, and x2, y2.

public void setLine(Point2D p1, Point2D p2)

This method sets the endpoints of the line to p1 and p2.

public void setLine(Line2D l)

This method sets the endpoints of the line to be the same as the endpoints of the given line.

Here are the constructors for the Line2D.Float class. Two of them allow you to specify the endpoints of the line, which saves you the trouble of calling setLine().

public Line2D.Float()

This constructor ...

Get Java 2D Graphics now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.