Basic technology:
There are many ways to implement animations in Java, but they do the same thing, by drawing a series of frames on the screen to create a sense of motion.
We first construct a program framework, and then slowly expand, so that the function is more complete.
To use a thread:
To update the screen more than once per second, you must create a thread to implement the animation loop, which tracks the current frame and responds to periodic screen update requirements. There are two ways to implement a thread, you can create a class thread derived class, or echo it on a runnable interface.
An easy mistake is to put the animation loop in Paint (), which occupies the main AWT thread, and the main thread is responsible for all the drawing and event handling.
A framework applet is as follows:
public
class Animator1 extends java.applet.Applet implements Runnable {
int frame;
int delay;
Thread animator;
public void init() {
String str = getParameter("fps");
int fps = (str != null) ? Integer.parseInt(str) : 10;
delay = (fps > 0) ? (1000 / fps) : 100;
}
public vois start() {
animator = new Thread(this);
animator.start();
}
public void run() {
while (Thread.currentThread() == animator) {
repaint();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
}
frame++;
}
}
public void stop() {
animator = null;
}
}
Quote this in your HTML file:
<applet code=Animator1.class width=200 height=200>
<param name=fps value=200>
</applet>
The parameter fps above indicates the number of frames per second
Maintain a constant frame speed:
In the example above, the applet only sleeps for a fixed amount of time between every two frames, but there are some drawbacks, sometimes you wait a long time, and you should not hibernate 100 milliseconds in order to display 10 frames per second, because it also takes time to run.
Here's an easy way to remedy this:
public void run() {
long tm = System.currentTimeMillis();
while (Thread.currentThread() == animator) {
repaint();
try {
tm += delay;
Thread.sleep(Math.max(0,tm -
System.currentTimeMillis()));
} catch (InterruptedException e) {
break;
}
frame++;
}
}