Java not only provides graphics, image support, but also allows users to achieve continuous image playback, that is, animation technology. Java animation implementation, first with the Graphics class in the java.awt package of the DrawImage () method to draw the image on the screen, and then by defining a thread, let the thread sleep for a period of time, and then switch to another image; Draw a series of frames on the screen to create a sense of motion, so as to achieve the purpose of displaying the animation.
In order 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, either by creating a class thread derived class, or by echoing on a runnable interface.
* Animation Tips
When you write an animation process, the most common problem is that the screen flashes. There are two reasons for flashing: First, it takes too long to draw each frame (because of the large amount of computation required for redrawing); the second is to repaint the entire screen with the background color before each call to pain (), and when the next frame is calculated, the user sees the background.
There are two ways to significantly weaken flicker: overload update () or use double buffering.
(1) Overload update ()
When AWT receives a redraw request for an applet, it invokes the applet's update (), by default, update () clears the applet's background, and then invokes paint (). Overload update () to include the drawing code that was previously in paint () in update () to avoid clearing the entire area each time it is redrawn. The following is the original program code for the Update () method:
public void update(Graphics g)
{
//首先用背景色来绘制整个画面
g.setColor(getBackGround());
g.fillRect(0,0,width,height);
//接着设置前景色为绘制图像的颜色,然后调用paint()方法
g.setColor(getForeGround());
paint(g);
}
So to eliminate the flicker of the screen must overwrite the update () method, so that the method does not clear the entire screen, but only to eliminate the necessary parts.