java applet例子---跟踪图片对象的加载

用java.awt包中的MediaTracker跟踪一个Image对象的装载,可以保证所有图片都加载完毕。

package applet;

import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;

public class MyMediaTracker extends Applet implements Runnable, ActionListener {

	Button loadB;
	Thread runner;
	MediaTracker tracker;

	Image im1, im2;

	boolean bothok = false;

	@Override
	public void run() {
		Object[] errArray;
		tracker = new MediaTracker(this);
		
		System.out.println("codeBase:"+this.getCodeBase());
		try {
//			this.getCodeBase()是.../java项目名称(此applet所在的java项目)/bin/
			im1 = this.getImage(new URL(this.getCodeBase(),"jiangnan.jpg"));
			im2 = this.getImage(new URL(this.getCodeBase(),"happiness.jpg"));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		tracker.addImage(im1, 0);
		tracker.addImage(im2, 0);
		
		try {
			tracker.waitForID(0);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		if(tracker.checkAll()){
			System.out.println("checkAll() is true");
		}
		else{
			System.out.println("checkAll() is false");
		}
		if(tracker.isErrorAny()){
			System.out.println("There is error in Tracker!");
			if((tracker.statusAll(false)&MediaTracker.ERRORED)!=0){
				System.out.println("图片在加载过程中出现错误");
			}
			else {
				System.out.println("图片在加载过程中没有出现错误");
			}
			
			if((tracker.statusAll(false)&MediaTracker.ABORTED)!=0){
				System.out.println("图片在加载过程中被中断");
			}
			else {
				System.out.println("图片在加载过程中没有被中断");
			}
			
			if((tracker.statusAll(false)&MediaTracker.COMPLETE)!=0){
				System.out.println("图片已被加载完成");
			}
			else {
				System.out.println("图片没有被加载完成");
			}
			
			if((tracker.statusAll(false)&MediaTracker.LOADING)!=0){
				System.out.println("图片还在加载中");
			}
			else {
				System.out.println("图片未在加载中");
			}
			
			errArray  = tracker.getErrorsID(0);
			for(int i = 0;i<errArray.length;i++){
				if(errArray[i]==im1){
					System.out.println("图片1发生错误");
				}
				if(errArray[i]==im2){
					System.out.println("图片2发生错误");
				}
			}
		} //出错
		
		else {
			System.out.println("没有发生错误");
		}
		repaint();
		bothok = true;
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
if(e.getSource() ==loadB){
	if(runner ==null){
		runner = new Thread(this);
		runner.start();
	}
}
	}
	
	public void init(){
		loadB = new Button("load");
		loadB.addActionListener(this);
		this.add(loadB);
	}

	public void paint(Graphics g) {
		if (bothok) {
			g.drawImage(im1, 20, 70, this);
			g.drawImage(im2,400, 50, this);
		}
	}

}

执行结果:

codeBase:file:/E:/Eclipse%20workspace/DataStructSample/bin/
checkAll() is true
没有发生错误

其中%20代表着空格符号

你可能感兴趣的:(java,eclipse,thread,.net)