home *** CD-ROM | disk | FTP | other *** search
/ Learn Java Now / Learn_Java_Now_Microsoft_1996.iso / JavaNow / Code / Chap16 / Animation / Animation.java < prev    next >
Encoding:
Java Source  |  1996-07-29  |  11.6 KB  |  331 lines

  1. //******************************************************************************
  2. // Animation.java:    Applet
  3. //
  4. //******************************************************************************
  5. import java.applet.*;
  6. import java.awt.*;
  7.  
  8. //==============================================================================
  9. // Main Class for applet Animation
  10. //
  11. //==============================================================================
  12. public class Animation extends Applet implements Runnable
  13. {
  14.     // THREAD SUPPORT:
  15.     //        m_Animation    is the Thread object for the applet
  16.     //--------------------------------------------------------------------------
  17.     Thread     m_Animation = null;
  18.  
  19.     // ANIMATION SUPPORT:
  20.     //        m_Graphics        used for storing the applet's Graphics context
  21.     //        m_Images[]        the array of Image objects for the animation
  22.     //        m_nCurrImage    the index of the next image to be displayed
  23.     //        m_ImgWidth        width of each image
  24.     //        m_ImgHeight        height of each image
  25.     //        m_fAllLoaded    indicates whether all images have been loaded
  26.     //        m_numImages         number of images used in the animation
  27.     //--------------------------------------------------------------------------
  28.     private Graphics m_Graphics;
  29.     private Image     m_Images[];
  30.     private int      m_nCurrImage;
  31.     private int      m_nImgWidth  = 0;
  32.     private int      m_nImgHeight = 0;
  33.     private boolean  m_fAllLoaded = false;
  34.     // private final int m_numImages = 18;
  35.  
  36.     private int    m_nSleepTime;  // sleep time based on m_fps
  37.     
  38.     // PARAMETER SUPPORT:
  39.     //        Parameters allow an HTML author to pass information to the applet;
  40.     // the HTML author specifies them using the <PARAM> tag within the <APPLET>
  41.     // tag.  The following variables are used to store the values of the
  42.     // parameters.
  43.     //--------------------------------------------------------------------------
  44.  
  45.     // Members for applet parameters
  46.     // <type>       <MemberVar>    = <Default Value>
  47.     //--------------------------------------------------------------------------
  48.     private int m_fps = 10;
  49.     private String m_imageFile = "";
  50.     private int m_numImages = 22;
  51.  
  52.     // Parameter names.  To change a name of a parameter, you need only make
  53.     // a single change.  Simply modify the value of the parameter string below.
  54.     //--------------------------------------------------------------------------
  55.     private final String PARAM_fps = "fps";
  56.     private final String PARAM_imageFile = "imageFile";
  57.     private final String PARAM_numImages = "numImages";
  58.  
  59.     // Animation Class Constructor
  60.     //--------------------------------------------------------------------------
  61.     public Animation()
  62.     {
  63.         // TODO: Add constructor code here
  64.     }
  65.  
  66.     // APPLET INFO SUPPORT:
  67.     //        The getAppletInfo() method returns a string describing the applet's
  68.     // author, copyright date, or miscellaneous information.
  69.     //--------------------------------------------------------------------------
  70.     public String getAppletInfo()
  71.     {
  72.         return "Name: Animation\r\n" +
  73.                "Author: Stephen R. Davis\r\n" +
  74.                "Created for Learn Java Now (c)";
  75.     }
  76.  
  77.     // PARAMETER SUPPORT
  78.     //        The getParameterInfo() method returns an array of strings describing
  79.     // the parameters understood by this applet.
  80.     //
  81.     // Animation Parameter Information:
  82.     //  { "Name", "Type", "Description" },
  83.     //--------------------------------------------------------------------------
  84.     public String[][] getParameterInfo()
  85.     {
  86.         String[][] info =
  87.         {
  88.             { PARAM_fps, "int", "Frame rate" },
  89.             { PARAM_imageFile, "String", "Name of the image seq" },
  90.             { PARAM_numImages, "int", "Number of images" },
  91.         };
  92.         return info;        
  93.     }
  94.  
  95.     // The init() method is called by the AWT when an applet is first loaded or
  96.     // reloaded.  Override this method to perform whatever initialization your
  97.     // applet needs, such as initializing data structures, loading images or
  98.     // fonts, creating frame windows, setting the layout manager, or adding UI
  99.     // components.
  100.     //--------------------------------------------------------------------------
  101.     public void init()
  102.     {
  103.         // PARAMETER SUPPORT
  104.         //        The following code retrieves the value of each parameter
  105.         // specified with the <PARAM> tag and stores it in a member
  106.         // variable.
  107.         //----------------------------------------------------------------------
  108.         String param;
  109.  
  110.         // fps: Frame rate
  111.         //----------------------------------------------------------------------
  112.         param = getParameter(PARAM_fps);
  113.         if (param != null)
  114.             m_fps = Integer.parseInt(param);
  115.  
  116.         // imageFile: Name of the image seq
  117.         //----------------------------------------------------------------------
  118.         param = getParameter(PARAM_imageFile);
  119.         if (param != null)
  120.             m_imageFile = param;
  121.  
  122.         // numImages: Number of images
  123.         //----------------------------------------------------------------------
  124.         param = getParameter(PARAM_numImages);
  125.         if (param != null)
  126.             m_numImages = Integer.parseInt(param);
  127.  
  128.         // If you use a ResourceWizard-generated "control creator" class to
  129.         // arrange controls in your applet, you may want to call its
  130.         // CreateControls() method from within this method. Remove the following
  131.         // call to resize() before adding the call to CreateControls();
  132.         // CreateControls() does its own resizing.
  133.         //----------------------------------------------------------------------
  134.         resize(320, 240);
  135.  
  136.         // Calculate the sleep time based on fps
  137.         if (m_fps != 0)
  138.         {
  139.             m_nSleepTime = 1000 / m_fps;
  140.         }
  141.     }
  142.  
  143.     // Place additional applet clean up code here.  destroy() is called when
  144.     // when you applet is terminating and being unloaded.
  145.     //-------------------------------------------------------------------------
  146.     public void destroy()
  147.     {
  148.         // TODO: Place applet cleanup code here
  149.     }
  150.  
  151.     // ANIMATION SUPPORT:
  152.     //        Draws the next image, if all images are currently loaded
  153.     //--------------------------------------------------------------------------
  154.     private void displayImage(Graphics g)
  155.     {
  156.         if (!m_fAllLoaded)
  157.             return;
  158.  
  159.         // Draw Image in center of applet
  160.         //----------------------------------------------------------------------
  161.         g.drawImage(m_Images[m_nCurrImage],
  162.                    (size().width - m_nImgWidth)   / 2,
  163.                    (size().height - m_nImgHeight) / 2, null);
  164.         // display the frame number (this is optional)
  165.         g.setColor(Color.white);
  166.         g.drawString("Image #" + m_nCurrImage, 10,40);
  167.     }
  168.  
  169.     // Animation Paint Handler
  170.     //--------------------------------------------------------------------------
  171.     public void paint(Graphics g)
  172.     {
  173.         // ANIMATION SUPPORT:
  174.         //        The following code displays a status message until all the
  175.         // images are loaded. Then it calls displayImage to display the current
  176.         // image.
  177.         //----------------------------------------------------------------------
  178.         if (m_fAllLoaded)
  179.         {
  180.             Rectangle r = g.getClipRect();
  181.             
  182.             g.clearRect(r.x, r.y, r.width, r.height);
  183.             displayImage(g);
  184.         }
  185.         else
  186.             g.drawString("Loading images...", 10, 20);
  187.  
  188.         // TODO: Place additional applet Paint code here
  189.     }
  190.  
  191.     //        The start() method is called when the page containing the applet
  192.     // first appears on the screen. The AppletWizard's initial implementation
  193.     // of this method starts execution of the applet's thread.
  194.     //--------------------------------------------------------------------------
  195.     public void start()
  196.     {
  197.         if (m_Animation == null)
  198.         {
  199.             m_Animation = new Thread(this);
  200.             m_Animation.start();
  201.         }
  202.         // TODO: Place additional applet start code here
  203.     }
  204.     
  205.     //        The stop() method is called when the page containing the applet is
  206.     // no longer on the screen. The AppletWizard's initial implementation of
  207.     // this method stops execution of the applet's thread.
  208.     //--------------------------------------------------------------------------
  209.     public void stop()
  210.     {
  211.         if (m_Animation != null)
  212.         {
  213.             m_Animation.stop();
  214.             m_Animation = null;
  215.         }
  216.  
  217.         // TODO: Place additional applet stop code here
  218.     }
  219.  
  220.     // THREAD SUPPORT
  221.     //        The run() method is called when the applet's thread is started. If
  222.     // your applet performs any ongoing activities without waiting for user
  223.     // input, the code for implementing that behavior typically goes here. For
  224.     // example, for an applet that performs animation, the run() method controls
  225.     // the display of images.
  226.     //--------------------------------------------------------------------------
  227.     public void run()
  228.     {
  229.         m_nCurrImage = 0;
  230.         
  231.         // If re-entering the page, then the images have already been loaded.
  232.         // m_fAllLoaded == TRUE.
  233.         //----------------------------------------------------------------------
  234.         if (!m_fAllLoaded)
  235.         {
  236.             repaint();
  237.             m_Graphics = getGraphics();
  238.             m_Images   = new Image[m_numImages];
  239.  
  240.             // Load in all the images
  241.             //------------------------------------------------------------------
  242.             MediaTracker tracker = new MediaTracker(this);
  243.             String strImage;
  244.  
  245.             // For each image in the animation, this method first constructs a
  246.             // string containing the path to the image file; then it begins
  247.             // loading the image into the m_Images array.  Note that the call to
  248.             // getImage will return before the image is completely loaded.
  249.             //------------------------------------------------------------------
  250.             for (int i = 1; i <= m_numImages; i++)
  251.             {
  252.                 // Build path to next image
  253.                 //--------------------------------------------------------------
  254.                 // the AppletWizard code uses a hard-coded filename;
  255.                 // replace with a parameter from the HTML file
  256.                 strImage = // "images/img00"
  257.                            m_imageFile       // initialized in init()
  258.                            + ((i < 10) ? "0" : "") 
  259.                            + i
  260.                            + ".gif";
  261.                 m_Images[i-1] = getImage(getDocumentBase(), strImage);
  262.  
  263.                 tracker.addImage(m_Images[i-1], 0);
  264.             }
  265.  
  266.             // Wait until all images are fully loaded
  267.             //------------------------------------------------------------------
  268.             try
  269.             {
  270.                 tracker.waitForAll();
  271.                 m_fAllLoaded = !tracker.isErrorAny();
  272.             }
  273.             catch (InterruptedException e)
  274.             {
  275.                 // TODO: Place exception-handling code here in case an
  276.                 //       InterruptedException is thrown by Thread.sleep(),
  277.                 //         meaning that another thread has interrupted this one
  278.             }
  279.             
  280.             if (!m_fAllLoaded)
  281.             {
  282.                 stop();
  283.                 m_Graphics.drawString("Error loading images!", 10, 40);
  284.                 return;
  285.             }
  286.             
  287.  
  288.             // Assuming all images are same width and height.
  289.             //--------------------------------------------------------------
  290.             m_nImgWidth  = m_Images[0].getWidth(this);
  291.             m_nImgHeight = m_Images[0].getHeight(this);
  292.         }        
  293.         repaint();
  294.  
  295.         // get the audio clip that goes with the animation above
  296.         String sSoundClip = new String(m_imageFile + ".au");
  297.         AudioClip ac = getAudioClip(getCodeBase(), sSoundClip);
  298.  
  299.         // now play it in a loop
  300.         ac.loop();
  301.  
  302.         while (true)
  303.         {
  304.             try
  305.             {
  306.                 // Draw next image in animation
  307.                 //--------------------------------------------------------------
  308.                 displayImage(m_Graphics);
  309.                 m_nCurrImage++;
  310.                 if (m_nCurrImage == m_numImages)
  311.                     m_nCurrImage = 0;
  312.  
  313.                 // replace with a value based on the fps parameter:
  314.                 Thread.sleep(m_nSleepTime);
  315.             }
  316.             catch (InterruptedException e)
  317.             {
  318.                 // TODO: Place exception-handling code here in case an
  319.                 //       InterruptedException is thrown by Thread.sleep(),
  320.                 //         meaning that another thread has interrupted this one
  321.                 stop();
  322.             }
  323.         }
  324.     }
  325.  
  326.  
  327.  
  328.     // TODO: Place additional applet code here
  329.  
  330. }
  331.