Java Reference
In-Depth Information
g2D.drawString("p1", p1.x-20, p1.y);
g2D.drawString("p2", p2.x+10, p2.y);
}
}
GradientPane pane = new GradientPane(); // Pane containing filled rectangles
}
If you run this applet with the following HTML, you should get the window shown above.
<applet code="GradientApplet.class" width=400 height=280></applet>
Note that to get a uniform color gradation, your monitor needs to be set up for at least 16 bit (65536
colors) colors, preferably 24 bits (16.7 million colors).
How It Works
To import the individual class names that are used in this example needs nine import statements so here
we just import all the class names in each of the three packages. As a rule, it is better practice to only
import the class names that you use in your code, but we will use the
*
form to import all the names in
a package when this reduces the number of import statements significantly.
The applet displays two rectangles, and they are annotated to indicate which is which. The applet also
displays the gradient lines, which lie in the middle of the rectangles. You can see the cyclic and acyclic
gradients quite clearly. You can also see how points off the gradient line have the same color as the
normal projection onto the line.
The first block of shaded code in the
paint()
method creates the upper rectangle where the
GradientPaint
object that is used is
g1
. This is created as a cyclic gradient between the points
p1
and
p2
varying from white to dark gray. These shades have been chosen because the topic is in black
and white, but you can try any color combination you like. To set the color gradient for the fill, we call
setPaint()
for the
Graphics2D
object and pass
g1
to it. Any shapes drawn and/or filled subsequent
to this call will use the gradient color, but here we just fill the rectangle,
rect1
.
To make the outline and the annotation clearer, we set the current color back to black before calling the
draw()
method to draw the outline of the rectangle, and the
drawString()
method to annotate it.
The code for the lower rectangle is essentially the same as that for the first. The only important
difference is that we specify the last argument to the constructor as
false
to get an acyclic gradient.
This causes the colors of the ends of the gradient line to be the same as the end points. We could have
omitted the Boolean parameter here, and got an acyclic gradient by default.
The applet shows how points off the gradient line have the same color as the normal projection onto the
line. This is always the case regardless of the orientation of the gradient line. Try changing the definition
of
g1
for the upper rectangle to:
GradientPaint g1 = new GradientPaint(p1.x, p1.y - 20, Color.WHITE,
p2.x, p2.y + 20, Color.DARK
_
GRAY,
true); // Cyclic gradient