Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
How Graphics2D renders: the stroke, transform, clip, fill and compose pipeline, rendering hints, the Shape hierarchy with Float and Double classes, rectangles, ellipses, arcs, curves, Path2D with winding rules, and combining shapes with Area.
kvi5hnuCode Sprout team member20 min readOn this page
The first Java versions offered a Graphics class with methods such as drawRect and fillOval: integer coordinates, one-pixel lines, solid colors, no rotation. Java 2D, added in Java 1.2 and still the drawing engine under every Swing component, replaced that with a model borrowed from PostScript and PDF: geometry is described by shape objects with floating-point coordinates, and a graphics context decides how those shapes become pixels. This article covers the geometry side and the pipeline; the next one covers the individual pipeline settings (strokes, paints, transforms, clipping and transparency).
From Graphics to Graphics2D
Graphics2D is a subclass of Graphics. Since Java 1.2, every Graphics object that Swing passes to paintComponent is really a Graphics2D, and so is the object returned by BufferedImage.createGraphics(). A cast unlocks the richer API:
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g;
Shape box = new Rectangle2D.Double(10.5, 20, 100, 40.25);
g2.draw(box); // outline
g2.fill(box); // interior
}
Instead of one method per figure, there are two that take any Shape: draw traces the outline, fill paints the inside. Everything else (line width, color or gradient, rotation, transparency) is state held in the Graphics2D object.
A typical drawing routine therefore looks like this:
- Obtain a
Graphics2D(cast theGraphicsparameter, or callcreateGraphicson an image). When you change many settings, work on a copy made withg.create()anddispose()it at the end, so the settings do not leak into the painting of other components. - Set rendering hints, which trade speed for quality.
- Set the stroke used for outlines (
setStroke). - Set the paint used to fill (
setPaint): a color, a gradient or a texture. - Restrict the drawing area if needed (
clip). - Set a transformation from user to device coordinates (
translate,scale,rotate,shear,transform). - Set a composition rule for combining new pixels with existing ones (
setComposite). - Create shapes and call
draworfill.
var g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3f));
g2.setPaint(Color.BLUE);
g2.clip(new Ellipse2D.Double(0, 0, 200, 200));
g2.rotate(Math.toRadians(15));
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2.fill(new Rectangle2D.Double(20, 20, 120, 60));
g2.dispose();
The setters draw nothing; they only change the context. The steps above are a convenient order to write the settings in. The order in which they are applied is fixed by the pipeline.
The rendering pipeline

When you call draw(shape) or fill(shape), the shape passes through these stages:
- Stroke (only for
draw): the outline is turned into a new shape, the region a pen of the current stroke covers when it traces the path. A 3-pixel wide line becomes a thin filled polygon. After this step bothdrawandfillare fills. - Transform: the shape is mapped from user space, the coordinates your code uses, to device space, the pixels of the screen, image or printer page. The transform includes any translation, scaling or rotation you set, plus what the system adds itself, such as the HiDPI scale factor on a Retina or 4K display.
- Clip: whatever lies outside the clip area is discarded.
- Fill: the remaining area is colored with the current paint, pixel by pixel. Rendering hints decide whether edges are antialiased.
- Compose: each new pixel is combined with the pixel already on the surface according to the composite rule. The default simply covers it, but with transparency the colors blend.
The demo shows the stages together: a rectangle 20 units wide, stroked 2 units wide, shifted by (2, 1), with the right part cut off by a clip.
Text goes through the same pipeline: a glyph is just a shape provided by the font, so rotated, gradient-filled or clipped text needs no special API.
Rendering hints
The pipeline often has a choice between a fast and a good way of doing something. Rendering hints tell it what you prefer. A hint is a key/value pair; keys and values are constants in RenderingHints:
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
The most useful ones:
| Key | Values | Effect |
|---|---|---|
KEY_ANTIALIASING | VALUE_ANTIALIAS_ON, _OFF, _DEFAULT | Smooth shape edges by partially covering edge pixels. |
KEY_TEXT_ANTIALIASING | VALUE_TEXT_ANTIALIAS_ON, _OFF, _GASP, _LCD_HRGB, _LCD_HBGR, _LCD_VRGB, _LCD_VBGR, _DEFAULT | Smooth text; the LCD values use subpixel rendering. |
KEY_TEXT_LCD_CONTRAST | an Integer from 100 to 250 | Contrast for LCD text. |
KEY_FRACTIONALMETRICS | VALUE_FRACTIONALMETRICS_ON, _OFF, _DEFAULT | Position glyphs with fractional rather than rounded advances. |
KEY_RENDERING | VALUE_RENDER_QUALITY, _SPEED, _DEFAULT | General quality preference. |
KEY_STROKE_CONTROL | VALUE_STROKE_PURE, _NORMALIZE, _DEFAULT | PURE draws strokes at their exact geometry; NORMALIZE may nudge them to pixel boundaries for consistent thin lines. |
KEY_INTERPOLATION | VALUE_INTERPOLATION_NEAREST_NEIGHBOR, _BILINEAR, _BICUBIC | How pixels are computed when images are scaled or rotated. |
KEY_ALPHA_INTERPOLATION, KEY_COLOR_RENDERING | _QUALITY, _SPEED, _DEFAULT | Precision of blending and color conversion. |
KEY_DITHERING | VALUE_DITHER_ENABLE, _DISABLE, _DEFAULT | Approximate colors on displays with few colors. |
KEY_RESOLUTION_VARIANT | VALUE_RESOLUTION_VARIANT_DEFAULT, _BASE, _SIZE_FIT, _DPI_FIT | Which image of a multi-resolution image to use (Java 9 and later). |
RenderingHints implements Map<Object, Object>, so several hints can be collected and applied at once with setRenderingHints(map) (replace all) or addRenderingHints(map) (merge).
They are hints: an implementation may ignore them. The OpenJDK renderer honors antialiasing, stroke control and interpolation reliably; others such as dithering matter only on unusual displays. Antialiasing has a visible cost in edge sharpness for axis-aligned lines, which is why Swing does not turn it on for shapes by default. Text antialiasing, on the other hand, is usually set from the desktop settings (the awt.font.desktophints property of the toolkit), and Swing components apply it automatically.
The demo fills a small circle with antialiasing off and on. Without it every pixel is either in or out, so the edge is jagged; with it the edge pixels are partly covered and get intermediate gray levels.
The shape hierarchy
All geometric figures implement the java.awt.Shape interface, which answers geometric questions: contains(x, y) and contains(rect), intersects(rect), getBounds() (integer) and getBounds2D() (floating point), and above all getPathIterator, which walks the outline as a sequence of line and curve segments. The renderer needs nothing else, so your own classes can implement Shape too.
The java.awt.geom package provides these shapes:
Line2D: a line segment.Rectangle2D,RoundRectangle2D,Ellipse2D,Arc2D: the rectangular shapes. They extend the abstract classRectangularShape, which stores a bounding rectangle (the frame) and offersgetX,getY,getWidth,getHeight,getCenterX,getCenterY,getMinX/getMaxX,setFrame,setFrameFromDiagonalandsetFrameFromCenter.QuadCurve2DandCubicCurve2D: Bézier curves of degree two and three.Path2D: an arbitrary sequence of lines and curves. Its subclassGeneralPathis the class name from Java 1.2; since Java 6 it is justPath2D.Floatwith an older name.Area: a region built from other shapes by set operations.
In addition, java.awt still has the integer classes from Java 1.0, Rectangle, Polygon and Point, which were retrofitted to fit the hierarchy: Rectangle extends Rectangle2D and Point extends Point2D, while Polygon implements Shape directly. For new code, Path2D is more flexible than Polygon.
Point2D is not a shape (a point has no area); it describes locations such as the corners and control points passed to shape constructors.
Float and Double
Each geometry class except Area has two concrete static inner classes, Float and Double, which store coordinates as float or double:
Rectangle2D floatRect = new Rectangle2D.Float(5F, 10F, 7.5F, 15F);
Rectangle2D doubleRect = new Rectangle2D.Double(5, 10, 7.5, 15);
The outer class is abstract and declares getters returning double, so code that only reads the shape does not care which is used. The float variants halve the memory for programs that keep millions of shapes; the price is the F suffixes and casts when setting values, because Rectangle2D.Float has setRect(float, float, float, float). Use Double unless memory really matters; the renderer works in float internally anyway.
The demo prints the classes with their bounds. Two details stand out. The arc's bounds cover only the part of the ellipse the arc actually uses. And the cubic curve's bounds go down to y = -2.9 although its control point is at y = -10: since JDK 19, getBounds2D of curves returns the tight bounds of the curve itself rather than the box around all control points (JDK-8176501). Older JDKs returned the larger box.
Rectangles, ellipses and rounded rectangles
Rectangle2D, Ellipse2D and RoundRectangle2D are created from the top-left corner, width and height of their frame. For an ellipse, that is the bounding box, not the center:
var r = new Rectangle2D.Double(150, 200, 100, 50);
var e = new Ellipse2D.Double(150, 200, 100, 50); // fits exactly inside r
var e2 = new Ellipse2D.Double(r.getX(), r.getY(), r.getWidth(), r.getHeight());
If you know two opposite corners but not which is top-left, setFrameFromDiagonal(x1, y1, x2, y2) (or with two Point2Ds) sorts that out. For a circle or an ellipse around a known center, setFrameFromCenter(centerX, centerY, cornerX, cornerY) takes the center and one corner of the frame:
var circle = new Ellipse2D.Double();
circle.setFrameFromCenter(cx, cy, cx + radius, cy + radius);
A RoundRectangle2D additionally takes the width and height of the ellipse that rounds the corners: new RoundRectangle2D.Double(150, 200, 100, 50, 20, 20) has corners shaped like quarters of a 20 by 20 circle. The demo renders a rounded rectangle and an ellipse in the same 20 by 8 frame.
Rectangle2D has handy extras: createIntersection and createUnion (the smallest rectangle containing both), add(point) to grow a rectangle so it contains a point, outcode(x, y) to tell on which sides a point lies outside, and intersectsLine.
Arcs
An Arc2D is a piece of the ellipse that fits in a frame. You give the frame, a start angle and an angular extent in degrees, measured counterclockwise from the positive x axis, plus a closure type:
var arc = new Arc2D.Double(150, 200, 100, 50, 30, 240, Arc2D.PIE);
Arc2D.OPEN: just the curve.Arc2D.CHORD: closed by the straight line between the end points.Arc2D.PIE: closed by two lines through the center, a pie slice.
When you fill an open arc, the fill implicitly closes it with the chord, so it fills like a CHORD arc; the difference shows only when drawing. The demo renders all three with the same angles.
The angle skew
For circular arcs, angles mean what you expect. For an elliptical frame, however, Arc2D treats the angles as if the frame were a square that was then stretched: an angle of 45 degrees always points at the corner of the frame, whatever its proportions. For a wide, flat ellipse, the actual direction from the center is flatter than the angle you passed. The demo uses a 40 by 10 ellipse: "start angle 30" begins at a point whose real direction from the center is only about 8 degrees.
To start an arc at a true geometric direction, convert the angle. Take any point (x, y) in the desired direction, measured from the center (with y growing downward as usual), and divide by the half axes a = width / 2 and b = height / 2 to undo the stretch:
double start = Math.toDegrees(Math.atan2(-y / b, x / a));
With that start angle, the demo's arc starts at exactly 30 degrees. The extent must be converted the same way, from the true end direction. (Arc2D also has setAngleStart(Point2D) and setAngles(x1, y1, x2, y2), which take points and perform this conversion for you.)
Quadratic and cubic curves
QuadCurve2D and CubicCurve2D describe Bézier curves, the curves used by every vector format from PostScript to SVG and fonts. A curve runs from a start point to an end point; control points pull it toward them without (in general) lying on it.
var quad = new QuadCurve2D.Double(startX, startY, controlX, controlY, endX, endY);
var cubic = new CubicCurve2D.Double(startX, startY, control1X, control1Y,
control2X, control2Y, endX, endY);
A quadratic curve has one control point, so it can only bend one way, like a parabola. A cubic curve has two and can form an S. The curve leaves the start point in the direction of the first control point and arrives at the end point from the direction of the last one, which is how drawing programs let you adjust curves with handles: the listing in this article does exactly that.
Mathematically, a quadratic curve is (1-t)²·P₀ + 2t(1-t)·C + t²·P₁ for t from 0 to 1. At t = 0.5 the curve is only halfway toward the control point, which the demo checks: the control point lies 20 units from the chord (getFlatness() reports that distance), but the curve only reaches 10.
Curves have methods for subdividing (subdivide splits a curve into two halves of the same type) and for measuring flatness. Renderers use them to approximate curves with short lines: getPathIterator(transform, flatness) returns a flattened iterator that contains only SEG_MOVETO, SEG_LINETO and SEG_CLOSE, with every curve replaced by line segments that deviate by at most flatness.
Paths
Path2D describes any outline as a sequence of segments:
var path = new Path2D.Double();
path.moveTo(10, 20); // start a new subpath
path.lineTo(20, 30); // straight line to a point
path.quadTo(30, 10, 40, 30); // quadratic curve: control point, end point
path.curveTo(50, 50, 60, 0, 70, 30); // cubic curve: two control points, end point
path.closePath(); // line back to the subpath's start
Every segment continues from the current point, the end of the previous one. A path may contain several unconnected subpaths, each begun by moveTo. closePath closes the current subpath; a path that is not closed is still filled as if closed by a line back to the start, but when drawn its ends get caps rather than a join.
getCurrentPoint() returns the current point; reset() empties the path for reuse. The coordinates passed are copied, so later changes to your variables do not affect the path; transform(at) changes the path's coordinates in place, and createTransformedShape(at) returns a transformed copy.
A polygon is a path of lineTo calls:
var polygon = new Path2D.Double();
polygon.moveTo(points[0].getX(), points[0].getY());
for (int i = 1; i < points.length; i++)
polygon.lineTo(points[i].getX(), points[i].getY());
polygon.closePath();
Appending shapes
append(shape, connect) adds the outline of another shape to the path. With connect false, the shape becomes separate subpaths. With connect true, its initial moveTo becomes a lineTo, joining it to the end of the current path. The demo appends a rectangle that way: the segment list changes from M L plus the rectangle's own M L L L Z into MLLLLLLZ, one connected outline.
Walking a path
Any shape's outline can be read back with a PathIterator. currentSegment(double[] coords) fills an array of at least six numbers and returns the segment type: SEG_MOVETO and SEG_LINETO use two coordinates, SEG_QUADTO four, SEG_CUBICTO six and SEG_CLOSE none. This is how a renderer, a printer driver or an SVG exporter consumes shapes, and how the demo lists the path it built.
Winding rules
When a path crosses itself, which points are inside? Picture a ray from the point out to infinity and look at the path edges it crosses. Java offers two rules, set with the constructor or setWindingRule:
WIND_EVEN_ODD: a point is inside if the ray crosses an odd number of edges. Overlapping regions alternate between inside and outside, so the center of a five-pointed star is a hole.WIND_NON_ZERO, the default: count +1 for each edge that crosses the ray going one way and -1 for each going the other way. A point is inside if the sum is not zero. The center of the star is circled twice in the same direction, so it is filled.
The demo fills the same star path under both rules. The choice also matters for shapes with holes: with NON_ZERO, an inner subpath only makes a hole if it runs in the opposite direction to the outer one; with EVEN_ODD, any nested subpath is a hole. SVG and PDF have the same two rules (evenodd and nonzero).
Constructive area geometry
Some outlines are hard to describe with paths but easy to describe as combinations: a ring is a circle minus a smaller circle, a keyhole is a circle plus a triangle. The Area class supports such constructive area geometry. Create an Area from any shape, then combine it with another Area:
| Operation | Result |
|---|---|
a.add(b) | union: points in a or b |
a.subtract(b) | difference: points in a but not in b |
a.intersect(b) | intersection: points in both |
a.exclusiveOr(b) | symmetric difference: points in exactly one |
var ring = new Area(new Ellipse2D.Double(0, 0, 100, 100));
ring.subtract(new Area(new Ellipse2D.Double(30, 30, 40, 40)));
g2.fill(ring);
The operations modify the Area they are called on. Area implements Shape, so the result can be drawn, filled, used as a clip or combined again. Internally it computes the actual boundary, so the outline of a union does not include the interior edges of the parts, and its path is closed and has no self-intersections.
An Area can answer structural questions: isEmpty, isRectangular, isPolygonal (only straight edges), and isSingular (one closed outline, without holes). The demo's ring is not singular, because it has a hole; two adjacent squares merge into a single rectangle. Area also has transform(at), createTransformedArea(at) and equals(Area), which compares geometry.
Area operations are exact but not cheap: they intersect every pair of edges. Build complex areas once, not on every repaint.
A shape editor
This program lets you pick a shape and drag its control points; the panel redraws the shape after each mouse movement, together with its tight bounding box (dashed). The shape recipes are records holding a lambda that turns an array of points into a Shape, so adding another kind of shape is one more array entry.
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.*;
import java.util.function.Function;
import javax.swing.*;
public final class ShapeEditor extends JFrame {
private static final long serialVersionUID = 1L;
/** A named recipe that turns control points into a shape. */
record Maker(String name, int points, Function<Point2D[], Shape> make) {
@Override public String toString() { return name; }
}
static final Maker[] MAKERS = {
new Maker("Cubic curve", 4, p -> new CubicCurve2D.Double(p[0].getX(), p[0].getY(),
p[1].getX(), p[1].getY(), p[2].getX(), p[2].getY(), p[3].getX(), p[3].getY())),
new Maker("Quadratic curve", 3, p -> new QuadCurve2D.Double(p[0].getX(), p[0].getY(),
p[1].getX(), p[1].getY(), p[2].getX(), p[2].getY())),
new Maker("Pie arc", 2, p -> {
var frame = new Rectangle2D.Double();
frame.setFrameFromDiagonal(p[0], p[1]);
return new Arc2D.Double(frame, 30, 270, Arc2D.PIE);
}),
new Maker("Polygon", 5, p -> {
var path = new Path2D.Double(Path2D.WIND_EVEN_ODD);
path.moveTo(p[0].getX(), p[0].getY());
for (int i = 1; i < p.length; i++) path.lineTo(p[i].getX(), p[i].getY());
path.closePath();
return path;
}),
new Maker("Two circles, exclusive or", 2, p -> {
var a = new Area(new Ellipse2D.Double(p[0].getX() - 60, p[0].getY() - 60, 120, 120));
a.exclusiveOr(new Area(new Ellipse2D.Double(p[1].getX() - 60, p[1].getY() - 60, 120, 120)));
return a;
}),
};
static final class ShapePanel extends JComponent {
private static final long serialVersionUID = 1L;
private static final int HANDLE = 8;
private transient Maker maker;
private transient Point2D[] points;
private int dragged = -1;
ShapePanel() {
setPreferredSize(new Dimension(500, 400));
var mouse = new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
for (int i = 0; i < points.length; i++)
if (points[i].distance(e.getPoint()) <= HANDLE) dragged = i;
}
@Override public void mouseReleased(MouseEvent e) { dragged = -1; }
@Override public void mouseDragged(MouseEvent e) {
if (dragged < 0) return;
points[dragged] = e.getPoint();
repaint();
}
};
addMouseListener(mouse);
addMouseMotionListener(mouse);
}
void setMaker(Maker m) {
maker = m;
points = new Point2D[m.points()];
for (int i = 0; i < points.length; i++) { // start on a circle around the center
double angle = 2 * Math.PI * i / points.length - Math.PI / 2;
points[i] = new Point2D.Double(250 + 140 * Math.cos(angle), 200 + 140 * Math.sin(angle));
}
repaint();
}
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
Shape shape = maker.make().apply(points);
g2.setPaint(new Color(0xDCEBFF));
g2.fill(shape);
g2.setPaint(new Color(0x2563EB));
g2.setStroke(new BasicStroke(2f));
g2.draw(shape);
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f,
new float[] {4, 4}, 0));
g2.setPaint(Color.GRAY);
g2.draw(shape.getBounds2D()); // the (tight) bounding box
for (Point2D p : points) {
var handle = new Rectangle2D.Double(p.getX() - HANDLE / 2.0, p.getY() - HANDLE / 2.0, HANDLE, HANDLE);
g2.setPaint(Color.WHITE);
g2.fill(handle);
g2.setPaint(Color.BLACK);
g2.draw(handle);
}
g2.dispose();
}
}
public ShapeEditor() {
super("Shapes");
var panel = new ShapePanel();
var choice = new JComboBox<>(MAKERS);
choice.addActionListener(_ -> panel.setMaker(choice.getItemAt(choice.getSelectedIndex())));
panel.setMaker(MAKERS[0]);
var top = new JPanel();
top.add(new JLabel("Shape:"));
top.add(choice);
top.add(new JLabel("Drag the handles."));
add(top, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new ShapeEditor().setVisible(true));
}
}
Things to try: drag the cubic curve's control points across each other to form an S and a loop; move the polygon's points until edges cross and watch the even-odd rule create holes; overlap the two circles and pull them apart. The paint method works on a copy of the graphics context, as recommended, and turns on VALUE_STROKE_PURE so curves are drawn at their exact positions.
The program
The demo renders shapes into small grayscale images in headless mode and prints them as characters: # for a fully covered pixel, . for an empty one and + for a partly covered one (only when antialiasing is on). Rendering with antialiasing off gives the same pixels on every platform.
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) {
System.setProperty("java.awt.headless", "true");
pipeline();
hierarchy();
rectangularShapes();
arcs();
paths();
windingRules();
areas();
hints();
}
/** Fills the shape in a w x h image and prints '#' for covered pixels, '.' otherwise. */
static String render(Shape shape, int w, int h, boolean antialias) {
var image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
antialias ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(Color.WHITE);
g.fill(shape);
g.dispose();
var sb = new StringBuilder();
for (int y = 0; y < h; y++) {
sb.append(" ");
for (int x = 0; x < w; x++) {
int v = image.getRaster().getSample(x, y, 0);
sb.append(v == 255 ? '#' : v == 0 ? '.' : '+');
}
sb.append('\n');
}
return sb.toString();
}
static void show(String title, Shape shape, int w, int h) {
System.out.println(title);
System.out.print(render(shape, w, h, false));
}
static void pipeline() {
System.out.println("== The rendering pipeline on a 24 x 8 image ==");
var image = new BufferedImage(24, 8, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2 = image.createGraphics();
g2.setPaint(Color.WHITE); // paint
g2.setStroke(new BasicStroke(2f)); // stroke
g2.clip(new Rectangle(0, 0, 18, 8)); // clip
g2.transform(AffineTransform.getTranslateInstance(2, 1)); // transform: user -> device
Shape shape = new Rectangle2D.Double(0, 0, 20, 5); // shape in user coordinates
g2.draw(shape); // stroke, transform, clip, fill, compose
g2.dispose();
for (int y = 0; y < 8; y++) {
var sb = new StringBuilder(" ");
for (int x = 0; x < 24; x++) sb.append(image.getRaster().getSample(x, y, 0) > 0 ? '#' : '.');
System.out.println(sb);
}
System.out.println("(a 20 x 5 rectangle, stroked 2 wide, moved by (2, 1), clipped at x = 18)");
}
static void hierarchy() {
System.out.println();
System.out.println("== Shape classes ==");
Shape[] shapes = {
new Line2D.Double(0, 0, 10, 5), new Rectangle2D.Float(0, 0, 10, 5),
new RoundRectangle2D.Double(0, 0, 10, 5, 2, 2), new Ellipse2D.Double(0, 0, 10, 5),
new Arc2D.Double(0, 0, 10, 5, 0, 90, Arc2D.PIE), new QuadCurve2D.Double(0, 0, 5, 10, 10, 0),
new CubicCurve2D.Double(0, 0, 3, 10, 7, -10, 10, 0), new Path2D.Double(), new Area(),
new Polygon(new int[] {0, 4, 8}, new int[] {0, 6, 0}, 3), new Rectangle(1, 2, 3, 4)};
for (Shape s : shapes) {
Class<?> c = s.getClass();
String name = c.getEnclosingClass() != null ? c.getEnclosingClass().getSimpleName() + "." + c.getSimpleName()
: c.getSimpleName();
System.out.printf(" %-26s RectangularShape=%-5s bounds %s%n", name,
s instanceof RectangularShape, fmt(s.getBounds2D()));
}
var rect = new Rectangle2D.Double(5, 10, 7.5, 15);
System.out.println("contains (6, 11): " + rect.contains(6, 11) + ", intersects line: "
+ new Line2D.Double(0, 0, 20, 20).intersects(rect) + ", center " + rect.getCenterX() + ", " + rect.getCenterY());
}
static String fmt(Rectangle2D r) {
return "[%.1f, %.1f, %.1f x %.1f]".formatted(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
static void rectangularShapes() {
System.out.println();
System.out.println("== Rectangular shapes share a bounding rectangle ==");
show("rounded rectangle 20 x 8, corner arcs 8 x 6", new RoundRectangle2D.Double(1, 0, 20, 8, 8, 6), 22, 8);
var ellipse = new Ellipse2D.Double();
ellipse.setFrameFromCenter(11, 4, 1, 0); // the same frame, given by center and corner
show("ellipse in the same frame", ellipse, 22, 8);
}
static void arcs() {
System.out.println();
System.out.println("== Arcs: OPEN, CHORD and PIE closures ==");
String[] names = {"OPEN", "CHORD", "PIE"};
List<String[]> pictures = new ArrayList<>();
for (int type = Arc2D.OPEN; type <= Arc2D.PIE; type++)
pictures.add(render(new Arc2D.Double(0, 0, 14, 14, 30, 240, type), 14, 14, false).split("\n"));
System.out.printf(" %-16s %-16s %s%n", (Object[]) names);
for (int row = 0; row < 14; row++)
System.out.printf("%-18s %-16s %s%n", pictures.get(0)[row], pictures.get(1)[row].strip(), pictures.get(2)[row].strip());
System.out.println("(filling an OPEN arc closes it with a chord, so OPEN and CHORD fill alike; they differ when drawn)");
// Arc2D angles are skewed on non-circular frames. Find the point that truly lies
// in the direction 30 degrees from the center of a 40 x 10 ellipse...
double w = 40, h = 10, a = w / 2, b = h / 2, theta = Math.toRadians(30);
double scale = 1 / Math.hypot(Math.cos(theta) / a, Math.sin(theta) / b);
double px = scale * Math.cos(theta), py = -scale * Math.sin(theta); // y grows downward
var naive = new Arc2D.Double(-a, -b, w, h, 30, 60, Arc2D.OPEN);
Point2D n = naive.getStartPoint();
System.out.printf("Arc2D with start angle 30 starts at (%.2f, %.2f), true direction %.2f degrees%n",
n.getX(), n.getY(), Math.toDegrees(Math.atan2(-n.getY(), n.getX())));
// ...and convert it with normalized coordinates: angle = atan2(-y / b, x / a)
double start = Math.toDegrees(Math.atan2(-py / b, px / a));
var corrected = new Arc2D.Double(-a, -b, w, h, start, 60, Arc2D.OPEN);
Point2D c = corrected.getStartPoint();
System.out.printf("start angle %.2f starts at (%.2f, %.2f), true direction %.2f degrees%n",
start, c.getX(), c.getY(), Math.toDegrees(Math.atan2(-c.getY(), c.getX())));
}
static void paths() {
System.out.println();
System.out.println("== Paths: lines and curves ==");
var path = new Path2D.Double();
path.moveTo(0, 10);
path.lineTo(10, 0);
path.quadTo(20, -10, 30, 0);
path.curveTo(35, 5, 40, 15, 30, 20);
path.closePath();
path.moveTo(50, 0); // a second, unconnected piece
path.lineTo(60, 10);
String[] kinds = {"MOVETO", "LINETO", "QUADTO", "CUBICTO", "CLOSE"};
double[] c = new double[6];
for (PathIterator it = path.getPathIterator(null); !it.isDone(); it.next()) {
int type = it.currentSegment(c);
int n = switch (type) { case PathIterator.SEG_QUADTO -> 4; case PathIterator.SEG_CUBICTO -> 6;
case PathIterator.SEG_CLOSE -> 0; default -> 2; };
var sb = new StringBuilder(" " + kinds[type]);
for (int i = 0; i < n; i += 2) sb.append(" (%.0f, %.0f)".formatted(c[i], c[i + 1]));
System.out.println(sb);
}
int flat = 0;
for (PathIterator it = path.getPathIterator(null, 0.5); !it.isDone(); it.next()) flat++;
System.out.println("flattened to line segments (flatness 0.5): " + flat + " segments");
var withBox = new Path2D.Double();
withBox.moveTo(0, 0);
withBox.lineTo(5, 5);
withBox.append(new Rectangle2D.Double(10, 10, 4, 4), true); // connect with a line
System.out.println("append(rect, true) turns the rectangle's MOVETO into a LINETO: "
+ segments(withBox));
var quad = new QuadCurve2D.Double(0, 0, 10, 20, 20, 0);
double t = 0.5, midY = (1 - t) * (1 - t) * quad.y1 + 2 * t * (1 - t) * quad.ctrly + t * t * quad.y2;
System.out.printf("quad curve: flatness %.1f (control point's distance from the chord), but the curve "
+ "only reaches y = %.1f; tight getBounds2D height %.1f%n",
quad.getFlatness(), midY, quad.getBounds2D().getHeight());
}
static String segments(Shape s) {
String[] kinds = {"M", "L", "Q", "C", "Z"};
var sb = new StringBuilder();
for (PathIterator it = s.getPathIterator(null); !it.isDone(); it.next()) sb.append(kinds[it.currentSegment(new double[6])]);
return sb.toString();
}
static void windingRules() {
System.out.println();
System.out.println("== Winding rules for a self-intersecting path ==");
var star = new Path2D.Double();
for (int i = 0; i < 5; i++) {
double angle = Math.toRadians(-90 + i * 144);
double x = 15 + 14.5 * Math.cos(angle), y = 15.5 + 14.5 * Math.sin(angle);
if (i == 0) star.moveTo(x, y); else star.lineTo(x, y);
}
star.closePath();
star.setWindingRule(Path2D.WIND_EVEN_ODD);
String evenOdd = render(star, 30, 28, false);
star.setWindingRule(Path2D.WIND_NON_ZERO);
String nonZero = render(star, 30, 28, false);
String[] a = evenOdd.split("\n"), b = nonZero.split("\n");
System.out.printf(" %-31s %s%n", "WIND_EVEN_ODD", "WIND_NON_ZERO (default)");
for (int i = 0; i < a.length; i++) System.out.printf("%-33s %s%n", a[i], b[i].strip());
}
static void areas() {
System.out.println();
System.out.println("== Constructive area geometry with two circles ==");
Shape left = new Ellipse2D.Double(1, 1, 12, 12), right = new Ellipse2D.Double(8, 1, 12, 12);
String[] names = {"add", "subtract", "intersect", "exclusiveOr"};
List<String[]> pics = new ArrayList<>();
for (String op : names) {
var area = new Area(left);
var other = new Area(right);
switch (op) {
case "add" -> area.add(other);
case "subtract" -> area.subtract(other);
case "intersect" -> area.intersect(other);
default -> area.exclusiveOr(other);
}
pics.add(render(area, 21, 14, false).split("\n"));
}
System.out.printf(" %-23s %-23s%n", names[0], names[1]);
for (int r = 0; r < 14; r++) System.out.printf("%-25s %s%n", pics.get(0)[r], pics.get(1)[r].strip());
System.out.printf(" %-23s %-23s%n", names[2], names[3]);
for (int r = 0; r < 14; r++) System.out.printf("%-25s %s%n", pics.get(2)[r], pics.get(3)[r].strip());
var ring = new Area(new Ellipse2D.Double(0, 0, 10, 10));
ring.subtract(new Area(new Ellipse2D.Double(3, 3, 4, 4)));
System.out.println("ring: singular (one piece, no hole)? " + ring.isSingular()
+ ", rectangular? " + ring.isRectangular() + ", contains center? " + ring.contains(5, 5));
var square = new Area(new Rectangle(0, 0, 4, 4));
square.add(new Area(new Rectangle(4, 0, 4, 4)));
System.out.println("two adjacent squares merged: rectangular " + square.isRectangular()
+ ", bounds " + fmt(square.getBounds2D()));
}
static void hints() {
System.out.println();
System.out.println("== Rendering hints: antialiasing ==");
Shape circle = new Ellipse2D.Double(1, 1, 10, 10);
String off = render(circle, 12, 12, false), on = render(circle, 12, 12, true);
String[] a = off.split("\n"), b = on.split("\n");
System.out.printf(" %-14s %s%n", "OFF", "ON ('+' = partly covered)");
for (int i = 0; i < a.length; i++) System.out.printf("%-16s %s%n", a[i], b[i].strip());
var hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
System.out.println("hints map: " + hints.size() + " entries; antialiasing = "
+ hints.get(RenderingHints.KEY_ANTIALIASING));
}
}
== The rendering pipeline on a 24 x 8 image ==
.#################......
.#################......
.##.....................
.##.....................
.##.....................
.#################......
.#################......
........................
(a 20 x 5 rectangle, stroked 2 wide, moved by (2, 1), clipped at x = 18)
== Shape classes ==
Line2D.Double RectangularShape=false bounds [0.0, 0.0, 10.0 x 5.0]
Rectangle2D.Float RectangularShape=true bounds [0.0, 0.0, 10.0 x 5.0]
RoundRectangle2D.Double RectangularShape=true bounds [0.0, 0.0, 10.0 x 5.0]
Ellipse2D.Double RectangularShape=true bounds [0.0, 0.0, 10.0 x 5.0]
Arc2D.Double RectangularShape=true bounds [5.0, 0.0, 5.0 x 2.5]
QuadCurve2D.Double RectangularShape=false bounds [0.0, 0.0, 10.0 x 5.0]
CubicCurve2D.Double RectangularShape=false bounds [0.0, -2.9, 10.0 x 5.8]
Path2D.Double RectangularShape=false bounds [0.0, 0.0, 0.0 x 0.0]
Area RectangularShape=false bounds [0.0, 0.0, 0.0 x 0.0]
Polygon RectangularShape=false bounds [0.0, 0.0, 8.0 x 6.0]
Rectangle RectangularShape=true bounds [1.0, 2.0, 3.0 x 4.0]
contains (6, 11): true, intersects line: true, center 8.75, 17.5
== Rectangular shapes share a bounding rectangle ==
rounded rectangle 20 x 8, corner arcs 8 x 6
.....############.....
...#################..
..###################.
.####################.
.####################.
.####################.
..###################.
...#################..
ellipse in the same frame
......................
.....#############....
...#################..
..###################.
.####################.
..###################.
...#################..
.....#############....
== Arcs: OPEN, CHORD and PIE closures ==
OPEN CHORD PIE
.............. .............. ..............
....#######... ....#######... ....#######...
...#########.. ...#########.. ...#########..
..###########. ..###########. ..###########.
.############. .############. .############.
.############. .############. .##########...
.###########.. .###########.. .########.....
############.. ############.. #######.......
.##########... .##########... .######.......
.#########.... .#########.... .######.......
.#########.... .#########.... .######.......
..#######..... ..#######..... ..#####.......
...######..... ...######..... ...####.......
....####...... ....####...... ....###.......
(filling an OPEN arc closes it with a chord, so OPEN and CHORD fill alike; they differ when drawn)
Arc2D with start angle 30 starts at (17.32, -2.50), true direction 8.21 degrees
start angle 66.59 starts at (7.95, -4.59), true direction 30.00 degrees
== Paths: lines and curves ==
MOVETO (0, 10)
LINETO (10, 0)
QUADTO (20, -10) (30, 0)
CUBICTO (35, 5) (40, 15) (30, 20)
CLOSE
MOVETO (50, 0)
LINETO (60, 10)
flattened to line segments (flatness 0.5): 19 segments
append(rect, true) turns the rectangle's MOVETO into a LINETO: MLLLLLLZ
quad curve: flatness 20.0 (control point's distance from the chord), but the curve only reaches y = 10.0; tight getBounds2D height 10.0
== Winding rules for a self-intersecting path ==
WIND_EVEN_ODD WIND_NON_ZERO (default)
.............................. ..............................
.............................. ..............................
...............#.............. ...............#..............
...............#.............. ...............#..............
...............#.............. ...............#..............
..............###............. ..............###.............
..............###............. ..............###.............
..............###............. ..............###.............
.............#####............ .............#####............
.............#####............ .............#####............
.............#####............ .............#####............
............#######........... ............#######...........
...#########.......#########.. ...#########################..
....########.......########... ....#######################...
......#####.........#####..... ......###################.....
.......####.........####...... .......#################......
.........##.........##........ .........#############........
.............................. ..........###########.........
..........#.........#......... ..........###########.........
..........###.....###......... ..........###########.........
.........#####...#####........ .........#############........
.........######.######........ .........#############........
.........#####...#####........ .........#####...#####........
........#####.....#####....... ........#####.....#####.......
........###.........###....... ........###.........###.......
........##...........##....... ........##...........##.......
.......##.............##...... .......##.............##......
.............................. ..............................
== Constructive area geometry with two circles ==
add subtract
..................... .....................
..................... .....................
....##############... ....#######..........
...################.. ...#######...........
..##################. ..#######............
..##################. ..#######............
..##################. ..#######............
.###################. .#######.............
..##################. ..#######............
..##################. ..#######............
..##################. ..#######............
...################.. ...#######...........
....##############... ....#######..........
..................... .....................
intersect exclusiveOr
..................... .....................
..................... .....................
..................... ....##############...
..........##......... ...#######..#######..
.........####........ ..#######....#######.
.........####........ ..#######....#######.
.........####........ ..#######....#######.
........#####........ .#######.....#######.
.........####........ ..#######....#######.
.........####........ ..#######....#######.
.........####........ ..#######....#######.
..........##......... ...#######..#######..
..................... ....##############...
..................... .....................
ring: singular (one piece, no hole)? false, rectangular? false, contains center? false
two adjacent squares merged: rectangular true, bounds [0.0, 0.0, 8.0 x 4.0]
== Rendering hints: antialiasing ==
OFF ON ('+' = partly covered)
............ ............
............ ...++++++...
....#####... ..+######+..
...#######.. .+########+.
..#########. .+########+.
..#########. .+########+.
.##########. .+########+.
..#########. .+########+.
..#########. .+########+.
...#######.. ..+######+..
....#####... ...++++++...
............ ............
hints map: 2 entries; antialiasing = Antialiased rendering mode
Points to notice:
- In the pipeline picture, the 2-unit stroke straddles the rectangle's outline (one unit on each side), the translation moved everything by (2, 1), and the clip cut off everything from x = 18 onward, including the right edge.
- Only the four frame-based shapes and the legacy
RectangleareRectangularShapes. The emptyPath2DandAreahave empty bounds. - The
OPENandCHORDarcs fill identically; thePIEarc fills the slice to the center. - Arc angle 30 on the 40 by 10 ellipse pointed in the direction 8.21 degrees; the converted start angle 66.59 pointed at exactly 30.
- The 19 flattened segments replace two curves; the straight segments and the separate subpath are passed through unchanged.
- The star differs only in its center pentagon: a hole under even-odd, filled under non-zero.
isSingularis false for the ring because of its hole, and the two adjacent squares merged into a rectangle without an inner edge.
Common questions
Should I use Graphics methods or Graphics2D shapes?
Graphics2D with shape objects for anything beyond trivial drawing: floating-point coordinates, transforms, strokes and gradients all apply uniformly, and shapes can be reused for hit testing.
How do I test whether a click hit a shape?
shape.contains(point) for filled shapes. For outlines or lines, test against the stroked shape: new BasicStroke(6).createStrokedShape(line).contains(point), which gives a tolerance of 3 pixels on each side.
How do I draw a shape with a hole?
Build an Area and subtract the hole, or put both outlines into one Path2D with WIND_EVEN_ODD.
Why are my thin lines blurry?
With antialiasing on, a 1-pixel line at an integer coordinate straddles two pixel rows. Use KEY_STROKE_CONTROL with VALUE_STROKE_NORMALIZE (the default) for crisp axis-aligned lines, or offset coordinates by 0.5. VALUE_STROKE_PURE gives exact geometry but softer edges.
How do I export my shapes to SVG?
Walk each shape's PathIterator and write M, L, Q, C and Z commands into an SVG path element, with fill-rule matching the winding rule. Libraries such as JFreeSVG implement a full Graphics2D that produces SVG.
API reference
| Class / method | Purpose |
|---|---|
Graphics2D.draw(Shape), fill(Shape), create(), dispose() | Drawing outlines and interiors; working on a copy of the context. |
setRenderingHint(key, value), getRenderingHint, setRenderingHints(Map), addRenderingHints(Map), RenderingHints | Quality preferences. |
setStroke, setPaint, clip, transform/translate/rotate/scale/shear, setComposite | Pipeline settings (next article). |
Shape.contains, intersects, getBounds, getBounds2D, getPathIterator(at), getPathIterator(at, flatness) | Geometric queries and outline iteration. |
RectangularShape.getX/getY/getWidth/getHeight/getCenterX/getCenterY, setFrame, setFrameFromDiagonal, setFrameFromCenter | Frame-based shapes. |
Line2D, Rectangle2D, RoundRectangle2D, Ellipse2D, Arc2D, QuadCurve2D, CubicCurve2D, each with .Float and .Double | Shape classes. |
Arc2D(x, y, w, h, start, extent, type), OPEN, CHORD, PIE, getStartPoint, setAngleStart(Point2D), setAngles | Arcs. |
Path2D.Double/Float, GeneralPath, moveTo, lineTo, quadTo, curveTo, closePath, append(shape, connect), getCurrentPoint, reset, transform, createTransformedShape | Paths. |
Path2D.WIND_EVEN_ODD, WIND_NON_ZERO, setWindingRule | Inside test for self-intersecting paths. |
PathIterator.currentSegment(double[]), next, isDone, SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, SEG_CLOSE | Reading an outline. |
Area(Shape), add, subtract, intersect, exclusiveOr, isEmpty, isRectangular, isPolygonal, isSingular, createTransformedArea | Constructive area geometry. |
Point2D.Double/Float, distance; legacy Rectangle, Polygon, Point | Points and integer shapes. |
Summary
- Cast
GraphicstoGraphics2Dand describe geometry withShapeobjects;drawstrokes the outline,fillpaints the interior. - Every shape goes through the same pipeline: stroke (for
draw), transform from user to device space, clip, fill with the paint, compose with existing pixels. The setters only change the context. - Rendering hints request quality such as antialiasing, pure strokes or bicubic interpolation; implementations may ignore them.
- Shape classes come in
FloatandDoublevariants; rectangles, rounded rectangles, ellipses and arcs share a frame. Arc angles are relative to the frame and skewed for non-circular ellipses. - Bézier curves are shaped by control points;
Path2Dcombines lines and curves into subpaths, with the even-odd or non-zero winding rule deciding the inside.PathIteratorreads any outline back. Areacombines shapes by union, difference, intersection and exclusive or.
Practice Questions
1. A paintComponent method sets a 5-pixel stroke and a rotation on its Graphics2D parameter. Afterwards the borders of other components look wrong. Why, and how should the method be written?
The Graphics object passed to paintComponent is shared with the painting of the component's border and children, so settings changed on it remain in effect after the method returns. The method should call var g2 = (Graphics2D) g.create();, change and draw with the copy, and call g2.dispose() at the end. (Resetting each setting by hand also works but is easy to get wrong, especially with transforms.)
2. In what order are the stroke, transform and clip applied, and what follows from that order for a 2-pixel line drawn while the context is scaled by 3?
The stroke comes first, in user space; the result is then transformed to device space and clipped. So the 2-unit line becomes a 2-unit wide outline shape, which the scale turns into a 6-pixel wide band. Strokes scale with the transform. If you want a hairline that stays 1 pixel wide whatever the zoom, transform the shape yourself (createTransformedShape) and draw it with an identity transform.
3. Why do the geometry classes have Float and Double inner classes, and which should you use?
The abstract outer class (for example Rectangle2D) declares the API with double getters, and the inner classes store the coordinates as float or double. Float saves memory when a program keeps very many shapes; Double is more precise and more convenient, because double literals and arithmetic need no casts or F suffixes. Use Double by default and declare variables with the outer type.
4. A five-pointed star is drawn with one moveTo, four lineTo calls and closePath. Filled, it shows a pentagon-shaped hole in the middle. What determines this, and how do you get a solid star?
The winding rule. The path's lines cross, and under WIND_EVEN_ODD a ray from the central pentagon crosses an even number of edges, so the pentagon counts as outside. Under WIND_NON_ZERO (the default for Path2D) the edges around the center all turn the same way, the winding count is 2, and the star is filled solid. Use new Path2D.Double() or setWindingRule(Path2D.WIND_NON_ZERO).
5. How do you build a ring and a keyhole outline with the API, and why is Area better than drawing the parts on top of each other?
Ring: var ring = new Area(outerCircle); ring.subtract(new Area(innerCircle));. Keyhole: var key = new Area(circle); key.add(new Area(triangle));. Painting the parts over each other only works with an opaque paint and an opaque background: it cannot make a real hole (the background must show through), and drawing the outline would show the inner edges of the parts. An Area is a single shape with the true combined boundary, so it can be filled with any paint, stroked, used as a clip or tested with contains.
Previous: Swing Trees: JTree, Tree Models, Nodes and Paths
Next: Java 2D Strokes, Paint, Transforms, Clipping and Transparency
Related reading
- Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
- Java Logging Handlers, Filters and Formatters: Configuring java.util.logging
- Java Logging Basics: System.Logger and java.util.logging
- Java Assertions: Using assert, Enabling Assertions and Design by Contract
- Java Exception Handling Best Practices: Tips Every Developer Should Know

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.