在超类中返回子类图像时返回空指针

时间:2017-03-20 05:06:35

标签: java image exception nullpointerexception null

我尝试编写空间入侵者并获得一个空指针(实体类的底部,在尝试加载每个实体的图像时触发getImageWidth()。我意识到这意味着图像文件为空,我只是无法弄清楚如何正确加载它。

有3个实体:外星人,子弹和玩家。实体类应该获取所有信息,子类调用其方法来加载图像。我有一种感觉,这是不对的,但我又不知道怎么回事。

import java.awt.image.BufferedImage;
import java.io.File;

public class Alien extends Entity implements Constants {
private File alienImageFile = new File(ALIEN_IMAGE_FILE_NAME);

public Alien(int x, int y) {
    this.setIsVisible(true);
    this.setx(x);
    this.sety(y);
    this.setdx(0);
    this.setdy(ALIEN_SPEED);
    this.setImageFromFile(alienImageFile);
}

//We don't want to reset the position of the alien if it goes out of bounds
public void checkHeightBounds() {
}
}

public class Entity implements Constants {
 private File defaultImageFile = new File(DEFAULT_IMAGE_FILE_NAME);
 private BufferedImage image;
 private int x;
 private int y;
 private int dx;
 private int dy;
 private int imageHeight;
 private int imageWidth;
 private boolean isVisible;


public void setImageHeight(int newImageHeight) {
    this.imageHeight = newImageHeight;
}

public void setImageWidth(int newImageWidth) {
    this.imageWidth = newImageWidth;
}

public int getdy() {
    return dy;
}

public BufferedImage getImage() { //this may not be safe
    return image;
}

public int getImageWidth() {
    if (!(this.getImage().equals(null))) {
        return this.getImage().getWidth();
    } else {
        return 0;
    }

public Entity(int x, int y) {
    this.setx(x);
    this.sety(y);
}
public void setImageFromFile(File file) {
    try {
        image = ImageIO.read(file);
    } catch (IOException e) {

    }
}

为了清晰起见,我删除了一些吸气剂和制定者。

0 个答案:

没有答案