我正在尝试为我的游戏背景加载图像,但 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 文件夹位于同一级别。