用线程在Applet实现图片动态显示 您所在的位置:网站首页 线程实现动画的方法 用线程在Applet实现图片动态显示

用线程在Applet实现图片动态显示

2024-06-26 23:01| 来源: 网络整理| 查看: 265

Keypoint:Thread,Graphics,Applet

通过在线程的run()方法中设置线程休眠时间并在Applet上显示图片,可以达到动态图效果。每个一段时间(线程休眠),实现一张图片或者一帧。费了不少时间才完成这个小程序,其中的许多注释是调试的时候添加的,为了保存完整思路,留在源代码中。

//Timer.java

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker;

public class Timer extends Applet {       int count, lastcount;        Image[] pictures;       Thread athread;

     public void init()

    {        count = 0;        lastcount = 10;        pictures = new Image[10];        this.setBackground(Color.gray);        this.setSize(300, 300);           MediaTracker tracker = new MediaTracker(this);        for (int i = 0; i < lastcount; i++) {

      //我用了十张图片,名称为1.jpg,2.jpg.....        pictures[i] = getImage(getCodeBase() ,new Integer(i).toString()+".jpg");       //System.out.println(getCodeBase() );       //System.out.println(pictures[i]);       tracker.addImage(pictures[i], 0);    }   tracker.checkAll(true);

 }

 public void start() {   Runnable target=new MyThread(1000);   athread = new Thread(target) ;   athread.start();   //System.out.println(athread.isAlive());  }  

 public void paint(Graphics g) {   g.setColor(Color.GREEN);   //g.draw3DRect(0, 0, count*100,count*100,true);      boolean done=g.drawImage(pictures[count++], 0, 0,300,300,null);   //g.drawImage         //g.drawString("Hello",100,100);   //System.out.println("paint method begun! and the result is:"+done);   if (count == lastcount) {    count = 0;   }

 }  

 private class MyThread implements Runnable {   int time;   volatile boolean run;

  public MyThread(int time) {    this.time = time;    run = true;   }

  public void run() {    while (run) {     try {      //System.out.println("thread begun!");      repaint();      Thread.sleep(time);     } catch (InterruptedException e) {     }    }   }  }

}

 

几个注意点:

1、图像文件必须放在与.class文件相同目录下!

2、Applet小程序在Eclipse开发环境中可以直接运行,但在其他情况下,需通过applet标签嵌入HTML文件中,在浏览器上运行。或者编译好之后用AppletViewer运行;



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有