你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
采用多线程制作动画
 

import java.awt.*;
import java.applet.*;

//注意到这个程序和Hello程序有什么不一样吗?在这个程序中多了implements Runnable。
public class carton extends Applet implements Runnable
{
Image img;
Thread thd = null;
int i;
int imgWidth = 150;
int imgHeight = 150;
int ncyc=1 ;

String namestr[] = new String[5] ;

//当线程被激活时开始运行run()函数。
public void run()
{
for (int j=0; j<5; j++)
{
namestr[j] = Integer.toString(j,8)+".jpg" ;
}

ncyc = -1 ;
while (true)
{
if (ncyc<=3) ncyc= ncyc+1 ; //初始化循环控制参数
else ncyc = 0 ;
img = getImage(getCodeBase(), namestr[ncyc]) ;

if (img != null)
{
i=imgHeight;
//repaint();
}

try {Thread.sleep(1000);} catch (InterruptedException e){}
i=0;
while (i<imgHeight)
{
repaint();
try {Thread.sleep(50);} catch (InterruptedException e){}
i+=4;
}
}
}

  //每次代码在新位置处重画位图,它都要调用repaint。该函数调用可重载的update方法。update方法与paint方法是相同的,这里为啥不用怕paint(Graphics g)呢?除了paint方法在绘图前要清除窗口,而update方法不清除(如果你把update方法改名为paint,你会看到有什么不同)。
public void update(Graphics g)
{
if (img != null)
{
g.clipRect(0, 0, imgWidth, i);
g.drawImage(img, 0, i - imgHeight, null);
}
}

public void start()
{
if (thd == null)
{
thd = new Thread(this);
thd.start();
}
}

public void stop()
{
thd = null;
} 

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089