• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Adding Animation

As you develop your user interfaces—particularly user interfaces for applets—you might find a need for animation. The previous section explored drawImage(); it is the graphical analog of drawString() that you've been using for a while. Listing 38.7 illustrates an animation technique you might consider using.

Code Listing 38.7. Animation1.java—This Applet Loads and Displays a Series of Images in Rapid Succession

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

public class Animation1 extends Applet implements Runnable {
    int  fFrame = -1;
    int  fDelay;
    Thread fThread;
    Image[] fEarth;

   public void init() {
      fEarth = new Image[30];
      String theString;
      int  theFramesPerSecond = 10;

     //load in the images
      for (int  i=1; i<=30; i++)
      {
      System.err.println("Starting load from " +
         getCodeBase() +
         " of ./Earth" + i +".gif");
          fEarth[i-1] = getImage (getCodeBase(),
                                 "./Earth"+i+".gif");
      }
//How many milliseconds between frames?
      theString = getParameter("fps");
      try {
        if (theString != null) {
            theFramesPerSecond = Integer.parseInt(theString );
        }
      } catch (NumberFormatException e) { }
      fDelay = (theFramesPerSecond > 0) ?
               (1000 / theFramesPerSecond) : 100;
    }

   public void start() {
      // start a new thread for the animation
      if (fThread == null) {
          fThread = new Thread(this);
      }
      fThread.start();
    }

   public void stop() {
      // stop the animation thread
      fThread = null;
    }

   public void run() {
      // run at a low priority; animation is second-place to content
      Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
      long theStartTime = System.currentTimeMillis();

     //Here comes the show.
      while (Thread.currentThread() == fThread) {

       //Advance the frame.
        fFrame++;

       //Display it.
        repaint();

       //Delay depending on how far we are behind.
        try {
             theStartTime += fDelay;
             Thread.sleep(Math.max(0,
                                   theStartTime-
                          System.currentTimeMillis()));
        } catch (InterruptedException e) {
                 break;
        }
    }
  }
//Draw the current frame
  public void paint(Graphics g) {
    g.drawImage(fEarth[fFrame % 30], 0, 0, this);
  }
}
					

					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint