Our first
example will be to create a Board object with 256 cells, each of which
will be filled with a different shade of gray. For the board to be square its dimensions
would be 16 by 16. To move from one cell
to another, we will use a nested loop as before. At every iteration,
we would need to create a new color object with an intensity that’s one
higher than the previous iteration.
Here’s the full program: import java.awt.Color; public class Grayscale { public static void main(String[] args) { int rows =
16, cols = 16; Board b = new Board(cols, rows); int intensity
= 0; for (int y =
0; y < rows; y++) { for (int x
= 0; x < cols; x++) { Color c = new Color(intensity, intensity,
intensity); b.fillCell(x,
y, c); b.pause(200); intensity++; } } } }
The board
object produced by the code is shown to the right. Starting with the top left hand corner, the
color is (0, 0, 0).
For a given row, the intensity increases by one for each horizontal
movement across the columns.
We can make
simple modifications to this program to obtain 256 variations of a particular
hue. Instead of making the three
primary color intensities vary together at every iteration,
we can choose to fix two of the three components and have the third be a
variable that is incremented with every loop iteration. Observe what happens (Board to the right)
when we fix the red intensity to 255 and green to 200, and allow the blue
intensity to increase. The code that
produced this board differs in one line: Color c = new Color(255, 200, intensity); |