Applets are small programs that run in a browser, and Java is also popular in the world from applets. By writing this applet, we can learn the following knowledge:
1. Applet and the main interface in JApplet
2. Image loading and Mediatracker use
3. Use of threads and direct communication with multiple threads
4. Use of the Thread.Join () method
5. Use of volatile keywords
First look at the running effect: click to run
The main part of the animation is an applet that reads a set of picture files from the codebase, and then rotates the display one at a 1-second intervals. The code is as follows:
import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Image;
Import Java.awt.MediaTracker;
public class Animate extends JApplet
{
//Picture quantity
private static final int num_of_pic = 4;
int count;
Image pics[];
TimerThread Timer;
public void init ()
{
count = 1;
pics = new Image[num_of_pic];
Mediatracker tracker = new Mediatracker (this);
for (int i = 0; i<num_of_pic; i++)
{
//to place the picture in the table of 0,1,..., num_of_pic-1, in the TOC, in the format. jpg
Pics[i] = GetImage (GetCodeBase (), New Integer (i). toString () + ". jpg");
Tracker.addimage (Pics[i], 0);
}
Tracker.checkall (true);
public void Start ()
{
Timer = new TimerThread (this, 1000);
Timer.start ();
}
public void Stop ()
{
Timer.shouldrun = false;
Try
{
Timer.join ();
Wait for the timer thread to exit
}
catch (Interruptedexception e) {};
public void Paint (Graphics g)
{
G.drawimage (pics[count++], 0, 0, null);
if (count = = num_of_pic) Count = 0;
}
}