Thread-controlled Animation

Source: Internet
Author: User


A thread is a part of a program and the basic unit of system scheduling. Threads are ideal for animation control. Place the animation work on the thread and release other parts of the program to process other tasks.
The reality of a Thread is that the Thread class in java. lang must implement the Runnable interface to enable a class to use a Thread. This interface contains the only method run (). The run () method is the core of the thread class. -------- motion is generated in the animation program. The run () method is called by calling the start () method of the thread. The program below depicts a circle in motion.

Import java. awt .*;
Import java. awt. event .*;
Import javax. swing .*;

Public class Cartoon extends JApplet implements Runnable
Graphics screenBuffer = null; // creates a graphic buffer.
Image screenImage = null;
Private Thread runner;
Private int x = 5;
Private int move = 1;

Public void init ()
ScreenImage = createImage (230,160 );
ScreenBuffer = screenImage. getGraphics ();
Public void start ()
If (runner = null)
Runner = new Thread (this );
Runner. start ();
Public void run ()
Thread circle = Thread. currentThread ();
While (runner = circle) // point to the same object and start running
X + = move;
If (x> 105) | (x <5 ))
Move * =-1;
Repaint ();
Public void drawCircle (Graphics gc)
Graphics2D g2D = (Graphics2D) gc;
G2D. setColor (Color. blue );
G2D. fillRect (0, 0,100,100 );
G2D. setColor (Color. yellow );
G2D. fillRect (100, 0,100,100 );
G2D. setColor (Color. red );
G2D. fillOval (x, 5, 90, 90 );
Public void paint (Graphics g)
ScreenBuffer. setColor (Color. white );
ScreenBuffer. fillRect );
DrawCircle (screenBuffer );
// Copy the image in the buffer zone to the master buffer zone
G. Fig (screenImage, 130,100, this );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.