Java animation programming foundation first part

zhaozj2021-02-08  451

Basic Technologies: There are many ways to achieve animations in Java, but the basic principles they achieve are the same, that is, draw a series of frames to create a feeling of motion on the screen. Let's construct a program framework, slowly expand, make it more complete. Use thread: For multiple update screens per second, you must create a thread to implement a loop of the animation, this loop to track the current frame and respond to periodic screen update requirements. There are two ways to implement threads, you can create a derived class of THREAD, or attached to the interface of Runnable. An easy-to-criminal error is to loop the animation in Paint (), which occupies the primary AWT thread, and the main thread will be responsible for all drawings and event processing. A frame applet follows: publicclass 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) {botch;} frame ;}} public void stop ()}} public void stop ()}} = NULL;}} In your html file, this reference: The above parameter fps represents frames per second The number remains constant: in the upper example, the applet is only a fixed time between each two frames, but this has some shortcomings, sometimes you will wait for a long time, for a ten frame image per second, should not sleep 100 milliseconds, because there is time in operation. Here is a simple remedy: 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) {breaf;} frame ;}}

转载请注明原文地址:https://www.9cbs.com/read-905.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.040, SQL: 9