1 30 31 package com.jgoodies.animation; 32 33 import java.awt.event.ActionEvent ; 34 import java.awt.event.ActionListener ; 35 36 import javax.swing.Timer ; 37 38 45 public final class Animator implements ActionListener { 46 47 private final Animation animation; 48 private final Timer timer; 49 private final int framesPerSecond; 50 51 private long startTime; 52 private long elapsedTime = 0; 53 54 55 57 66 public Animator(Animation animation, int framesPerSecond) { 67 if (animation == null) 68 throw new NullPointerException ("The animation must not be null."); 69 70 if (framesPerSecond <= 0) 71 throw new IllegalArgumentException ("The frame rate must be positive."); 72 73 this.animation = animation; 74 this.framesPerSecond = framesPerSecond; 75 this.timer = createTimer(framesPerSecond); 76 } 77 78 79 81 86 public Animation animation() { 87 return animation; 88 } 89 90 91 96 public int framesPerSecond() { 97 return framesPerSecond; 98 } 99 100 101 106 public long elapsedTime() { 107 return timer.isRunning() 108 ? System.currentTimeMillis() - startTime + elapsedTime 109 : elapsedTime; 110 } 111 112 113 116 public void start() { 117 if (!timer.isRunning()) { 118 registerStopListener(); 119 startTime = System.currentTimeMillis(); 120 timer.start(); 121 } 124 } 125 126 127 130 public void stop() { 131 if (timer.isRunning()) { 132 elapsedTime = elapsedTime(); 133 timer.stop(); 134 } 135 } 136 137 138 144 public void actionPerformed(ActionEvent e) { 145 animation.animate(elapsedTime()); 146 } 147 148 149 154 public String toString() { 155 return "elapsedTime=" + elapsedTime() + "; fps=" + framesPerSecond; 156 } 157 158 159 161 167 private Timer createTimer(int fps) { 168 int delay = 1000 / fps; 169 170 Timer aTimer = new Timer (delay, this); 171 aTimer.setInitialDelay(0); 172 aTimer.setCoalesce(true); 173 return aTimer; 174 } 175 176 177 180 private void registerStopListener() { 181 animation.addAnimationListener(new AnimationAdapter() { 182 public void animationStopped(AnimationEvent e) { 183 stop(); 185 } 187 }); 188 } 189 190 191 } | Popular Tags |