The Java 2D™ API provides a useful set of standard shapes such as points, lines, rectangles, arcs, ellipses, and curves. The most important package to define common geometric primitives is thejava.awt.geompackage. Arbitrary shapes can be represented by combinations of straight geometric primitives.The
Shapeinterface represents a geometric shape, which has an outline and an interior. This interface provides a common set of methods for describing and inspecting two-dimensional geometric objects and supports curved line segments and multiple sub-shapes. TheGraphicsclass supports only straight line segments. TheShapeinterface can support curves segments.For more details about how to draw and fill shapes, see the Working with Geometry lesson.
Points
ThePoint2Dclass defines a point representing a location in (x, y) coordinate space. The term “point” in the Java 2D API is not the same as a pixel. A point has no area, does not contain a color, and cannot be rendered.Points are used to create other shapes. The
Point2Dclass also includes a method for calculating the distance between two points.Lines
TheLine2Dclass is an abstract class that represents a line. A line’s coordinates can be retrieved as double. TheLine2Dclass includes several methods for setting a line’s endpoints.Also, you can create a straight line segment by using the
GeneralPathclass described below.Rectangular Shapes
TheRectangle2D,RoundRectangle2D,Arc2D, andEllipse2Dprimitives are all derived from theRectangularShapeclass. This class defines methods forShapeobjects that can be described by a rectangular bounding box. The geometry of aRectangularShapeobject can be extrapolated from a rectangle that completely encloses the outline of theShape.Quadratic and Cubic Curves
TheQuadCurve2Denables you to create quadratic parametric curve segments. A quadratic curve is defined by two endpoints and one control point.The
CubicCurve2Dclass enables you to create cubic parametric curve segments. A cubic curve is defined by two endpoints and two control points. The following are examples of quadratic and cubic curves. See Stroking and Filling for implementations of cubic and quadratic curves.This figure represents a quadratic curve.
This figure represents a cubic curve.
Arbitrary Shapes
TheGeneralPathclass enables you to construct an arbitrary shape by specifying a series of positions along the shape’s boundary. These positions can be connected by line segments, quadratic curves, or cubic (Bézier) curves. The following shape can be created with three line segments and a cubic curve. See Stroking and Filling for more information about the implementation of this shape.Areas
With theAreaclass, you can perform boolean operations, such as union, intersection, and subtraction, on any twoShapeobjects. This technique, often referred to as constructive area geometry, enables you to quickly create complexShapeobjects without having to describe each line segment or curve.