Java Reference
In-Depth Information
g2D.drawString("p2", p2.x+10, p2.y);
}
}
}
Directory "GradientApplet 1"
If you run this applet with the following HTML, you should get the window previously shown in Figure
19-20 :
<html>
<head>
</head>
<body bgcolor="000000">
<center>
<applet
code = "GradientApplet.class"
width = "400"
height = "280"
>
</applet>
</center>
</body>
</html>
Note that to get a nice smooth color gradation, your monitor needs to be set up for at least 16-bit colors
(65536 colors), and preferably 24-bit colors (16.7 million colors).
How It Works
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 nor-
mal projection onto the line.
The first block of 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 , and varying
from white to dark gray. I chose these shades because the topic is printed in black and white, but you
can try the example with any color combination you like. To set the color gradient for the fill, you call
setPaint() for the Graphics2D object and pass g1 to it. Any shapes that are drawn and/or filled subse-
quent to this call use the gradient color, but here you just fill the rectangle, rect1 .
To make the outline and the annotation clearer, you 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 you specify the last argument to the constructor as false to get an acyclic gradient fill pattern.
This causes the colors of the ends of the gradient line to be the same as the end points. You could have
omitted the boolean parameter here, getting an acyclic gradient by default.
Search WWH ::




Custom Search