Java Reference
In-Depth Information
More on graphics
13
In this chapter we discuss some techniques to improve drawings. This chapter can
be skipped on a first reading.
13.1
The class Graphics2D
In the previous examples for displaying drawings, we used the class Graphics
from the AWT library to supply the drawings commands. This class offers only
basic commands for drawing shapes. The line width, for example, is limited to one
pixel. To draw wider lines one can draw more than one line in parallel. One has to
consider the direction of the line in order to make this look nice. For thicker lines
one would also like to allow different kinds of line ends, e.g. rounded, square. This
and much more is provided by the class Graphics2D which is also found in the AWT
library. This class together with its helper classes such as Shape , AffineTransform
and Stroke provide very powerful methods to create and modify drawings. To
use it in paintComponent , one casts the Graphics parameter to Graphics2D .
As Graphics2D is derived from Graphics , all the 'old' drawing commands are
available.
A complete description of these classes is beyond the scope of this topic. We
restrict ourselves to a brief description of strokes. This is, in the author's experi-
ence, the feature that is most missed in class Graphics .A stroke may be thought
of as a drawing tool like a pen or a brush. The user can define such a tool with a
given width and shape and then use it to draw lines on curves. Besides this, one
can also set the line style. The use is quite simple: first define some strokes. Then
choose the desired one and all following drawing commands use it until another
stroke is selected.
Stokes in Java are realized by the interface Stroke . Java also supplies an im-
plementation of Stroke in the class BasicStroke . This class allows us to define
the line width, the line endings (rounded/square), and the way line segments are
connected to form a nice looking polygon. The width is specified by parame-
ter width in the constructors below, the style of the line end by parameter cap
and the joining method by join . For example to have rounded line ends one
Search WWH ::




Custom Search