在java.awt.Image时,getWidth()和getHeight()为-1的解决方法

import java.applet.*;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;

public class ImageRun extends Applet implements Runnable {
	Thread t;
	int w;
	Image img;
	
	public void init() {
		w = 0;
		img = getImage(getDocumentBase(),"image2.gif");
		
		setSize(600, 400);
	}
	
	public void start() {
		t = new Thread(this);
		t.start();
	}
	
	public void stop() {
		t = null;
	}
	
	public void run() {
		img   =   new ImageIcon(img).getImage();	//需要加入此代码
		int imgW = img.getWidth(null);
		System.out.println(imgW);
		while(t != null) {
			try{
				Thread.sleep(10);
				repaint();
				w++;
				if (w >= getWidth()) {
					w = -imgW;
				}
			} catch(Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}
	
	public void paint(Graphics g) {
		int h = getHeight() / 2;
		g.drawImage(img, w, h, this);
	}
	
	public void update(Graphics g) {
		paint(g);
	}
};

具体原因,可能是Image并没有加载具体图片,因此不能获取宽度和高度。

这是一菜鸟问题,高手如果看到这个问题,请顺便帮我解答一下,谢谢了~

你可能感兴趣的:(JAVA笔记)