// Programming Projects: Question 7.15
// Design and implement an applet that simulates
// the swinging movement of a pendulum.

import java.applet.Applet;
import java.awt.*;

public class Q7_23 extends Applet {

   public void paint (Graphics page) {

      // Number of pauses between each redraw
      final int PAUSE_TIME = 100000;

      // Number of swings to display
      final int NUM_SWINGS = 300;

      // Set applet background colour to white
      setBackground (Color.white);
      page.setXORMode (getBackground());

      // Pendulum arm will be drawn in black
      page.setColor (Color.black);

      // For each swing of the pendulum, draw a line at
      // several different positions on the applet.

      int x=100, y=200;  // starting bottom position of
                         // pendulum arm

      int direction = 1; // swing to right is 1, and
                         // swing to left is -1 to reverse

      for (int i=0; i<NUM_SWINGS; i++) {

         // Move x 5 units either left or right
         x = x + (direction*5);

         // Check to see if direction should be changed.
         if (x >= 300)
            direction = -1;
         else if (x <= 100)
            direction = 1;
       
         // Draw pendulum arm, pause, then redraw to
         // erase pendulum arm (due to XOR mode).
         // Note: Top of arm is always at (200,100).
         page.drawLine (200,100,x,200);
         for (int j=0; j<PAUSE_TIME; j++);
         page.drawLine (200,100,x,200);
      }
   }
}

