import java.awt.*; /* * Based on Arthur van Hoff's animation examples, this application * can serve as a template for all animation applications. */ public class AnimatorApplication extends Frame implements Runnable { int frameNumber; int delay; Thread animatorThread; AnimatorApplication(int fps, String windowTitle) { super(windowTitle); delay = (fps > 0) ? (1000 / fps) : 100; } public void startAnimation() { if (animatorThread == null) { animatorThread = new Thread(this); animatorThread.start(); } } public void stopAnimation() { animatorThread = null; } public boolean mouseDown(Event e, int x, int y) { if (animatorThread == null) { startAnimation(); } else { stopAnimation(); } return false; } public void run() { //Just to be nice, lower this thread's priority //so it can't interfere with other processing going on. Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Remember the starting time long startTime = System.currentTimeMillis(); while (Thread.currentThread() == animatorThread) { // Display the next frame of animation. repaint(); // Delay depending on how far we are behind. try { startTime += delay; Thread.sleep(Math.max(0, startTime-System.currentTimeMillis())); } catch (InterruptedException e) { break; } // Advance the frame frameNumber++; } } public void paint(Graphics g) { g.drawString("Frame " + frameNumber, 5, 50); } public static void main(String args[]) { AnimatorApplication animator = null; int fps = 10; // Get frames per second from the command line argument if (args.length > 0) { fps = Integer.parseInt(args[0]); } animator = new AnimatorApplication(fps, "Animator"); animator.resize(200, 60); animator.show(); animator.startAnimation(); } }