Java ImageIO异常

时间:2012-10-22 21:02:35

标签: java embedded-resource javax.imageio

虽然运行代码来显示pacman级别的背景,但我遇到了图像和pacman sprite无法加载的问题。

例外:

Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(ImageIO.java:1388)
    at org.pacman.Pacman.init(Pacman.java:51)
    at org.game.engine.GameLoop.run(GameLoop.java:26)

GameLoop第26行只是game.init();

这是班级:

public class Pacman extends Game {

    public static void main(String[] args) {
        GameApplication.start(new Pacman());
    }

    private BufferedImage sheet;
    private int frame;

    public Pacman() {
        title = "Pacman";
        width = 176;
        height = 258;
        frame = 0;
    }

    @Override
    public void draw(Graphics g) {
        if (sheet != null) {
            g.drawImage(sheet, -2, 0, null);
            //draw ms pacman
            g.drawImage(sheet.getSubimage(628+(frame/3)*(15+2), 33, 15, 15), 80, 105, null);
        }
    }

    @Override
    public void init() {
        try {
            sheet = ImageIO.read(Pacman.class.getResource("/images/pacman.png"));
        } catch (IOException ex) {
            Logger.getLogger(Pacman.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void update() {
        frame++;
        if (frame > 3*2) {
            frame = 0;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

  

at org.pacman.Pacman.init(Pacman.java:51)

请看第51行:

sheet = ImageIO.read(Pacman.class.getResource("/images/pacman.png"));

所以Pacman.class.getResource("/images/pacman.png")null,所以看起来它没有加载图片。

答案 1 :(得分:2)

尝试使用ImageIO.read调用getResourceAsStream,但请事先检查InputStream null。你会发现它确实是null。这意味着无法在该URI处检索图像。