Java Reference
In-Depth Information
Example 11•3: ColorGradient.java (continued)
bigFont = new Font("Helvetica", Font.BOLD, 72);
}
/** Draw the applet. The interesting code is in fillGradient() below */
public void paint(Graphics g) {
fillGradient(this, g, startColor, endColor); // display the gradient
g.setFont(bigFont); // set a font
g.setColor(new Color(100, 100, 200)); // light blue
g.drawString("Colors!", 100, 100);
// draw something interesting
}
/**
* Draw a color gradient from the top of the specified component to the
* bottom. Start with the start color and change smoothly to the end
**/
public void fillGradient(Component c, Graphics g, Color start, Color end) {
Rectangle bounds = this.getBounds(); // How big is the component?
// Get the red, green, and blue components of the start and end
// colors as floats between 0.0 and 1.0. Note that the Color class
// also works with int values between 0 and 255
float r1 = start.getRed()/255.0f;
float g1 = start.getGreen()/255.0f;
float b1 = start.getBlue()/255.0f;
float r2 = end.getRed()/255.0f;
float g2 = end.getGreen()/255.0f;
float b2 = end.getBlue()/255.0f;
// Figure out how much each component should change at each y value
float dr = (r2-r1)/bounds.height;
float dg = (g2-g1)/bounds.height;
float db = (b2-b1)/bounds.height;
// Now loop once for each row of pixels in the component
for(int y = 0; y < bounds.height; y++) {
g.setColor(new Color(r1, g1, b1)); // Set the color of the row
g.drawLine(0, y, bounds.width-1, y); // Draw the row
r1 += dr; g1 += dg; b1 += db;
// Increment color components
}
}
}
Simple Animation
Animation is nothing more than the rapid drawing of a graphic, with small
changes between “frames,” so the object being drawn appears to move. Example
11-4 shows the listing for an applet that performs a simple animation: it moves a
red circle around the screen. The applet uses a Thread object to trigger the
redraws. The technique used here is quite simple: when you run the applet, you
may notice that it flickers as the ball moves.
Later in this chapter, I'll show you another animation example that uses more
advanced techniques to prevent flickering and produce smoother animation.
Search WWH ::




Custom Search