1 package aurelienribon.utils.swing; 2 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 import javax.swing.JPanel; 6 import javax.swing.Timer; 7 8 /** 9 * @author Aurelien Ribon | http://www.aurelienribon.com 10 */ 11 public abstract class DrawingCanvas extends JPanel { 12 private final Timer timer; 13 private long lastMillis; 14 private Callback callback; 15 16 public DrawingCanvas() { 17 timer = new Timer(1000/60, loop); 18 timer.setRepeats(true); 19 } 20 21 protected abstract void update(int elapsedMillis); 22 23 public DrawingCanvas start() { 24 lastMillis = System.currentTimeMillis(); 25 timer.start(); 26 return this; 27 } 28 29 public void stop() { 30 timer.stop(); 31 } 32 33 public void setCallback(Callback callback) { 34 this.callback = callback; 35 } 36 37 private final ActionListener loop = new ActionListener() { 38 @Override public void actionPerformed(ActionEvent e) { 39 final long millis = System.currentTimeMillis(); 40 final long delta = millis - lastMillis; 41 lastMillis = millis; 42 43 update((int) delta); 44 if (callback != null) callback.onUpdate((int) delta); 45 } 46 }; 47 48 public interface Callback { 49 public void onUpdate(int elapsedMillis); 50 } 51 } 52