import java.awt.*; import java.applet.*;
public class AnimEx7 extends Applet implements Runnable { int frame; int delay; int step1=5,step2=2; Thread animator;
Dimension offDimension; Image offImage; Graphics offGraphics;
MediaTracker tracker;
Image image[] = new Image[10]; AudioClip bubble;
public void init() { String str = getParameter("fps"); int fps = (str != null) ? Integer.parseInt(str) : 10; delay = (fps > 0) ? (1000 / fps) : 100; tracker = new MediaTracker(this); for(int i=0; i<10; i++){ image[i]=getImage(getCodeBase(),"images/T"+(i+1)+".gif"); tracker.addImage(image[i],0); } bubble = getAudioClip(getCodeBase(),"images/bubble.au");
}
/** Create a thread and start it. */ public void start() { animator = new Thread(this); animator.start(); }
/** * the main animation. */ public void run() { // Remember the starting time long tm = System.currentTimeMillis(); while (Thread.currentThread() == animator) { // Display the next frame of animation. repaint(); // Delay depending on how far we are behind. try { tm += delay; Thread.sleep(Math.max(0,tm-System.currentTimeMillis())); } catch (InterruptedException e) {break; }
// Advance the frame frame++; } }
/** * called when the applet is no longer visible. */ public void stop() { animator = null; offImage = null; offGraphics = null; }
/** * Update a frame of animation. */ public void update(Graphics g) { Color fgr=getForeground(); Dimension d = getSize();
// Create the offscreen graphics context if ((offGraphics == null) || (d.width != offDimension.width) || (d.height != offDimension.height)) { offDimension = d; offImage = createImage(d.width, d.height); offGraphics = offImage.getGraphics(); }
// Erase the previous image offGraphics.setColor(getBackground()); offGraphics.fillRect(0, 0, d.width, d.height); offGraphics.setColor(fgr);
// Paint the frame into the image paintFrame(offGraphics);
// Paint the image onto the screen g.drawImage(offImage, 0, 0, this); }
public void paint(Graphics g) { update(g); }
/** * Paint a frame of animation. */ public void paintFrame(Graphics g) { // Only paint when all images have arrived if (tracker.statusID(0, true) == MediaTracker.COMPLETE) g.drawImage(image[frame % 10], 0, 0, this); // Play the bubble audio when Duke waves if ((frame % 10) == 3) bubble.play();
} }
|
|
|