Stroking Shape Outlines
Just as a
Graphics2D
object’s current paint
determines how its shapes are filled, its current stoke determines
how its shapes are outlined. The current stroke includes information
about line thickness, line dashing, and
end styles. (If you struggled with drawing in earlier versions of
Java, you’ll be very grateful that there’s now a way to
change the line thickness.)
To set the current stroke in a Graphics2D, just
call setStroke( ) with any implementation of the
Stroke interface. Fortunately, the 2D API includes
a BasicStroke
class that probably does everything you
need. Using BasicStroke, you can create dashed
lines, control what decoration is added to line ends, and decide how
the corners in an outline should be drawn.
By default, a Graphics2D uses a solid stroke with
a width of 1. In the previous Iguana example, the
line width is changed just before the outline of the rounded
rectangle is drawn, like so:
g2.setStroke(new BasicStroke(4));
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access