0

我正在尝试为我的游戏背景加载图像,但 Java 向我抛出了 NullPointerException 错误。我会评论它在哪里。

主要的:

public class Main {
    public static JFrame frame = new JFrame();
    public static final int windowXY[] = {800, 600};
    public static Dimension windowSize = new Dimension(windowXY[0], windowXY[1]);
    public static String windowName;
    public static String windowNames[] = {"Test1", "Test2"};
    public static Random roll = new Random();
    public static int nameRoll = roll.nextInt(2);
    public static Thread thread;
    public static boolean running;
    public static Graphics g;

    public static void main(String[] args) {
        start(g);
    }

    public static void start(Graphics g) {
        System.out.println("Starting up game...");
        windowName = windowNames[nameRoll];

        System.out.println("Loading window...");

        frame.setSize(windowSize);
        frame.setTitle(windowName);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        System.out.println("Finished loading window..");
        System.out.println("Loading textures...");

        MainImageRenderer.render();

        System.out.println("Finished loading textures...");
        System.out.println("Loading background...");

        //THROWS THE ERROR HERE
        MainImageRenderer.draw(g, MainImageRenderer.background, windowXY[0], windowXY[1]);     

        System.out.println("Finished loading background...");
    }
}

主图像渲染器:

public class MainImageRenderer extends Panel {

    public static Image background;

    public MainImageRenderer() {}

    public static void render() {
        try {
            Image background = ImageIO.read(new File("/resources/background.png"));
        }
        catch(IOException ie) {}
    }

    //THIS IS THE METHOD I AM USING 
    public static void draw(Graphics g, Image img, int x, int y) {
        g.drawImage(img, x, y, null);
    }

}

我不知道是不是我没有在正确的位置放置图像。我正在使用 Eclipse,并且资源文件夹与 src 文件夹位于同一级别。

4

3 回答 3

4

这部分代码是错误的:

try
{
    Image background = ImageIO.read(new File("/resources/background.png"));
}
catch(IOException ie)
{ 
}

background当你应该创建一个局部变量时

try
{
     background = ImageIO.read(new File("/resources/background.png"));
}
catch(IOException ie)
{
}

由于您隐藏了静态变量background,因此当您渲染图像时,background从未设置过。

而且正如 nybbler 评论的那样,g也将是null,这更直接导致您对NullPointerException.

于 2013-06-07T16:44:51.327 回答
0

background为空,因为ImageIO.read(...)正在抛出异常(您没有做任何事情)

于 2013-06-07T17:01:05.293 回答
0

删除多余的/,你很高兴....

new File("/resources/background.png")

改成

   new File("resources/background.png")

顺便推荐一下……这在你打包时很有帮助……

 URL url=this.getClass().getResource("resources/background.png");
 BufferedImage img = ImageIO.read(url);

看来您的代码有多个问题....

实例对象类型默认为null未初始化时...您g尚未使用非空对象初始化...

于 2013-06-07T16:53:35.473 回答