// OscillatingCheckerboard.java // Solution to Short Assignment 8 Extra Credit by THC. // Draws a checkerboard that oscillates between red and black squares // and green and white squares. import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.Timer; public class OscillatingCheckerboard extends Applet implements ActionListener { private final int DIMENSION = 8; // Want 8 x 8 board private final int SQUARE_SIZE = 30; // Each square is 30 x 30 pixels private Timer timer; // Timer for oscillation private boolean redAndBlack; // true if drawing red/black, false if green/white public void init() { // Set the size of the applet to be exactly the checkerboard size. setSize(DIMENSION * SQUARE_SIZE, DIMENSION * SQUARE_SIZE); redAndBlack = true; final int DELAY = 500; timer = new Timer(DELAY, this); timer.start(); // Draw the checkerboard. repaint(); } public void paint(Graphics page) { if (redAndBlack) drawCheckerboard(page, Color.black, Color.red); else drawCheckerboard(page, Color.white, Color.green); } // Draw a checkerboard in colors c1 and c2. public void drawCheckerboard(Graphics page, Color c1, Color c2) { // Draw all the squares. Color squareColor; // Color of the current square for (int row = 0; row < DIMENSION; row++) { for (int column = 0; column < DIMENSION; column++) { // A square is color c1 if the row and column numbers are both even // or both odd. Otherwise, the square is color c2. if (row % 2 == column % 2) squareColor = c1; else squareColor = c2; drawSquare(page, row, column, squareColor); } } } // Draw a given square of the checkerboard. Row and column numbers start // from 0. public void drawSquare(Graphics page, int row, int column, Color color) { page.setColor(color); page.fillRect(column * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE); } // Respond to a Timer event by drawing the checkerboard. public void actionPerformed(ActionEvent event) { redAndBlack = !redAndBlack; // oscillate repaint(); } }