The demonstration applet loads three images, called anim1.gif, anim2.gif, anim3.gif, from the base directory of the page from which the applet is loaded. If you'd like to modify the applet, you could increase the number of images, change the name or location, or change the speed of animation.
package org.best.example;
import java.applet.Applet;
import java.awt.*;
//
//
// MediaTrackerDemo
//
//
public class MediaTrackerDemo extends Applet implements Runnable
{
Image[] imgArray = null;
MediaTracker tracker = null;
int current = 0;
Thread animThread=null;
// Check for a mouse click, to start the images downloading
public boolean mouseDown(Event evt, int x, int y)
{
if (tracker == null)
{
// Create a new media tracker, to track loading images
tracker = new MediaTracker(this);
// Create an array of three images
imgArray = new Image[3];
// Start downloading the images
for (int index=0; index < 3; index++)
{
// Load the image
imgArray[index] = getImage( getDocumentBase(),
"anim" + (index+1) + ".gif");
// Register it with media tracker
tracker.addImage(imgArray[index], index);
}
// Start animation thread
animThread = new Thread(this);
animThread.start();
}
return true;
}
public void update(Graphics g) {
// Don't repaint gray background
paint(g);
}
public void paint (Graphics g)
{
g.setColor(Color.white);
g.fillRect(0,0, 200, 200);
g.setColor(Color.black);
// Check to see if images have started loading
if (tracker == null)
{
g.drawString ("Click to start loading",20,20);
}
else
// Check to see if images have loaded
if (tracker.checkAll())
{
g.drawImage(imgArray[current++], 0, 0, this);
if (current >= imgArray.length) current=0;
}
else
// Still loading
{
g.drawString ("Images are loading...", 20,20);
}
}
public void run()
{
try
{
tracker.waitForAll();
for (;;)
{
// Repaint the images
repaint();
Thread.sleep(2000);
}
}
catch (InterruptedException ie) {};
}
}
No comments:
Post a Comment