Applet是在浏览器中运行的小程序,Java也是从Applet开始风靡世界的。通过编写这个Applet,我们可以学习到如下知识:
1. Applet及JApplet中的主要接口
2. 图像的装载及MediaTracker的使用
3. 线程的使用及多个线程直接的通讯
4. Thread.join()方法的使用
5. volatile要害字的使用
首先看看运行效果:点击运行
动画的主要部分是一个Applet,从codebase中读取一组图片文件,然后每隔1秒轮换显示一张。代码如下:
import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
public class Animate extends JApplet
{
//图片数量
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++)
{
//将图片按照0,1,...,NUM_OF_PIC -1,放置在目录中,格式为.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();
//等待timer线程退出
}
catch (InterruptedException e){};
}
public void paint(Graphics g)
{
g.drawImage(pics[count++], 0, 0, null);
if(count == NUM_OF_PIC) count = 0;
}
}
动画的控制由一个专门的线程TimerThread进行处理,
import java.awt.Component;
public class TimerThread extends Thread
{
Component comp;
int timediff;
// shouldRun声明为volatile
volatileboolean shouldRun;
public TimerThread(Component comp, int timediff)
{
super("TimerThread(" + timediff + " millseconds");
this.comp = comp;
this.timediff = timediff;
shouldRun = true;
}
public void run()
{
while(shouldRun)
{
try
{
comp.repaint();
sleep(timediff);
}
catch (Exception e){}
}
}
}
Photoshop教程
数据结构
五笔输入法专题
QQ病毒专题
共享上网专题
Google工具和服务专题