// File name: Ch03Ex06Ans.java // This file contains a minimal shell for completing // DE Exercise 6 in Chapter 3. This program shell will // not produce any output until you add your code. // Note that this program is our first applet exercise. // Applets extend the Applet class, and don't have a // main method, since applets aren't applications. import java.awt.*; import java.applet.Applet; public class Ch03Ex06Ans extends SimpleAnimationApplet2 { /* Applet shows a checkerboard pattern in which the even numbered rows slide to the left and the odd numbered rows slide to the right. It is ASSUMED that the applet is 160x160 pixels, since the individual squares in the board are 20 pixels on a side. */ public void drawFrame(Graphics g) { // Draw one frame in the animation. int offset; // Amount by which the rows are offset from their usual // position. Even numbered rows are offset by this // amount to the left, odd numbered rows to the right. int row, col; // Row and column numbers, used as loop control variables. int x,y; // Top-left corner of a square. offset = getFrameNumber() % 40; // horizontal offset is in the range 0 to 39. for ( row = 0; row < 8; row++ ) { /* Draw one row. */ int leftEdge; // Position of left edge of this row, after it is offset from its // usual position. This is given by -40-offset if row is even // and by -40+offset if row is odd. if (row % 2 == 0) leftEdge = -40 - offset; else leftEdge = -40 + offset; /* Draw 12 squares per row, to make sure that the part of the row that is visible in the applet is completely filled with squares. When offset is zero, the row extends two squares to the left and two squares to the right of the applet, starting at x = -40. When offset > 0, the rows are offset by that amount to the left or right. */ for ( col = 0; col < 12; col++) { x = leftEdge + col * 20; y = row * 20; if ( (row % 2) == (col % 2) ) // Make colors alternate in a checkerboard fashion. g.setColor(Color.red); else g.setColor(Color.black); g.fillRect(x, y, 20, 20); } } // end for row } // end drawFrame() } // end class SlidingCheckerboard