
/*  
    SlidingSpectrum.class is a simple java applet that demonstrates the
    use of an "off-screen canvas" to produce smooth amination.  The entire
    area of the applet shows a color spectrum scrolling to the right.

BY:  David Eck
     Department of Mathematics and Computer Science
     Hobart and William Smith Colleges
     Geneva, NY   14456
     
     E-mail:  eck@hws.edu


NOTE:  YOU CAN DO ANYTHING YOU WANT WITH THIS CODE AND APPLET, EXCEPT
       TRY TO COPYRIGHT OR PATENT THEM YOURSELF.

*/


import java.awt.*;

public class SlidingSpectrum extends java.applet.Applet implements Runnable {

   Thread runner;   // thread to produce the animation

   Image OSC;  // the off-screen canvas
   
   public void start() {
      if (runner == null) {
         runner = new Thread(this);
         runner.start();
      }
   }
   
   public void stop() {
      if (runner != null) {
         runner.stop();
         runner = null;
      }
   }
   
   public void paint(Graphics g) {  // paint method just copies canvas to applet
      if (OSC != null)
         g.drawImage(OSC,0,0,this);
   }
   
   public void update(Graphics g) {  // replace standard update method so it doesn't
                                     // erase the screen
      paint(g);
   }
   

   public void run() {        // run method for animation thread

      int w = size().width;   // get the width and height of the applet
      int h = size().height;
      OSC = createImage(w,h);  // create an off screen canvas of the same size
      Graphics g = OSC.getGraphics();   // a graphics context for drawing to canvas

      Color[] colors = new Color[100];  // the colors of the spectrum
      int c = 0;  // for indexing the color array; c goes from 0 to 99 then back to 0

      for (int i=0; i<100; i++)   // create the colors
         colors[i] = Color.getHSBColor((float)(i*0.01), (float)1.0, (float)1.0);

      for (int i=w-1; i>=0; i--) {   // fill the canvas with a spectrum
         g.setColor(colors[c]);
         c++;
         if (c >= 99)
            c = 0;
         g.drawLine(i,0,i,h);
      }

      while (true) {

         g.copyArea(0,0,w-1,h,1,0);  // move contents of canvas one pixel right

         g.setColor(colors[c]);      // add a line of the next color, on the left
         c++;
         if (c >= 99)
            c = 0;
         g.drawLine(0,0,0,h);

         repaint();   // schedule the applet area for repainting

         try { Thread.sleep(50); }           // wait 1/20 second
         catch (InterruptedException e) { }

      }
   }

}

