package test;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Timer;
import java.util.TimerTask;
public class Test extends Applet {
/** milliseconds update for each paint */
private Object runLock = new Integer(1);
private static int intervalUpdate = 30;
private static int checkForInterval;
private long lastUpdateTime = 0;
private Image offImage;
private Dimension lastImageDim = null;
private Timer timer;
private TimerTask tt;
public Test() {
}
/*private void jbInit() throws Exception {
this.getContentPane().setLayout(null);
}*/
public void init() {
try {
intervalUpdate = Integer.parseInt(getParameter("INTERVAL_UPDATE"));
checkForInterval = intervalUpdate / 2;
timer = new Timer(true);
//jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(Graphics g) {
paint(g);
}
public void start() {
tt = new TimerTask() {
public void run() {
try {
synchronized(runLock) {
System.out.println("run");
long curr = System.currentTimeMillis();
if (curr - lastUpdateTime > intervalUpdate) {
Dimension dim = getSize();
int w = (int)dim.getWidth();
int h = (int)dim.getHeight();
if ((offImage == null ||
(lastImageDim != null && (lastImageDim.width != w ||
lastImageDim.height != h))) &&
(w != 0 && h != 0)) {
offImage = createImage(w, h);
/*while (offImage == null) {
Thread.sleep(50);
}*/
lastImageDim = new Dimension(w, h);
System.out.println("Image recreated");
}
if (offImage != null) {
Graphics g = offImage.getGraphics();
/* paint your stuff here */
g.setColor(new Color((int)(Math.random()*255),
(int)(Math.random()*255), (int)(Math.random()*255)));
g.drawString("Mona", 0, 20);
lastUpdateTime = curr;
update(getGraphics());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
timer.schedule(tt, 0, checkForInterval);
System.out.println("Start");
}
public void stop() {
tt.cancel();
timer.purge();
synchronized(runLock) {
System.out.println("Waited for timer to stop");
}
System.out.println("Stop");
}
public void destroy() {
System.out.println("Destroy");
}
public void paint(Graphics g) {
//int h = getHeight();
if (offImage != null) {
if (g != null)
g.drawImage(offImage, 0, 0, this);
}
}
}
|