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

4.2. Stroking

Stroking is the process of drawing the outline of a shape. Stroking is similar to painting:

  1. First, tell the Graphics2D how you want the outline to be drawn by calling setStroke(). This method accepts any object that implements the java.awt.Stroke interface. The 2D API comes with a class, java.awt.BasicStroke, that implements common stroking options.

  2. Use setPaint() to tell the Graphics2D how the outline itself should be drawn. Outlines, like the interior of shapes, can be drawn using a color, a gradient, a texture, or anything else that implements the Paint interface.

  3. Draw the outline of the shape using Graphics2D's draw() method. The Graphics2D uses the Stroke from step 1 to determine what the outline looks like. The Paint from step 2 is used to actually render the outline.

4.2.1. Stroke

Graphics2D uses a Stroke to figure out what the outline of a particular shape looks like. When you ask Graphics2D to draw() a shape, it asks its Stroke what the outline of the shape should look like. Interestingly, Stroke returns the stroked outline as another shape:

public abstract Shape createStrokedShape(Shape p)

This method returns a Shape that represents the stroked outline of the supplied shape.

This is the only method in Stroke. Usually, you won't call it yourself—a Graphics2D will call it on your behalf when you draw() a shape.

At first glance, it seems strange that the outline of a Shape is also a Shape. It may help to think of the outline of a Shape as an infinitesimally ...

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