Java Reference
In-Depth Information
Fig. 13.30
|
Testing
ShapesJPanel
. (Part 2 of 2.)
Ovals, Gradient Fills and
Paint
Objects
The first shape we draw is an
oval filled with gradually changing colors
. Lines 28-29 invoke
Graphics2D
method
setPaint
to set the
Paint
object that determines the color for the
shape to display. A
Paint
object implements interface
java.awt.Paint
. It can be some-
thing as simple as one of the predeclared
Color
objects introduced in Section 13.3 (class
Color
implements
Paint
), or it can be an instance of the Java 2D API's
GradientPaint
,
SystemColor
,
TexturePaint
,
LinearGradientPaint
or
RadialGradientPaint
classes. In
this case, we use a
GradientPaint
object.
Class
GradientPaint
helps draw a shape in
gradually changing colors
—called a
gra-
dient
. The
GradientPaint
constructor used here requires seven arguments. The first two
specify the starting coordinates for the gradient. The third specifies the starting
Color
for
the gradient. The fourth and fifth specify the ending coordinates for the gradient. The
sixth specifies the ending
Color
for the gradient. The last argument specifies whether the
gradient is
cyclic
(
true
) or
acyclic
(
false
). The two sets of coordinates determine the
direction of the gradient. Because the second coordinate (35, 100) is down and to the right
of the first coordinate (5, 30), the gradient goes down and to the right at an angle. Because
this gradient is cyclic (
true
), the color starts with blue, gradually becomes yellow, then
gradually returns to blue. If the gradient is acyclic, the color transitions from the first color
specified (e.g., blue) to the second color (e.g., yellow).
Line 30 uses
Graphics2D
method
fill
to draw a filled
Shape
object—an object that
implements interface
Shape
(package
java.awt
). In this case, we display an
Ellipse2D.Double
object. The
Ellipse2D.Double
constructor receives four arguments
specifying the
bounding rectangle
for the ellipse to display.
Rectangles,
Stroke
s
Next we draw a red rectangle with a thick border. Line 33 invokes
setPaint
to set the
Paint
object to
Color.RED
. Line 34 uses
Graphics2D
method
setStroke
to set the char-
acteristics of the rectangle's border (or the lines for any other shape). Method
setStroke
requires as its argument an object that implements interface
Stroke
(package
java.awt
).
In this case, we use an instance of class
BasicStroke
. Class
BasicStroke
provides several
constructors to specify the width of the line, how the line ends (called the
end caps
), how
lines join together (called
line joins
) and the dash attributes of the line (if it's a dashed
line). The constructor here specifies that the line should be 10 pixels wide.
Line 35 uses
Graphics2D
method
draw
to draw a
Shape
object—in this case, a
Rectangle2D.Double
. The
Rectangle2D.Double
constructor receives arguments speci-
fying the rectangle's
upper-left
x
-coordinate, upper-left
y
-coordinate, width and height.