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 );
}
}