简体   繁体   English

使用drawImage时(与Slick2d一起使用)NullPointerException

[英]NullPointerException when using drawImage (With Slick2d)

Have a bit of basic code put into the beginning of a game and have run into a bit of a hang with this nasty NullPointerException for no apparent reason. 在游戏开始时添加了一些基本代码,并且在没有明显原因的情况下,此讨厌的NullPointerException陷入了困境。

Loader.java (main class) Loader.java(主类)

public class Loader extends StateBasedGame {
public static final int menu = 0;
public static final int ingame = 1;

public Loader() {
    super("insertGameName");
    this.addState(new Menu(menu));
    this.addState(new Ingame(ingame));

}

public static void main(String args[]) throws SlickException {

    AppGameContainer gameContainer = new AppGameContainer(new Loader());
    gameContainer.setDisplayMode(rpg.Settings.WIDTH, rpg.Settings.HEIGHT, false);
    gameContainer.setVSync(true);
    try {
        gameContainer.start();
    } catch (SlickException e) {
        e.printStackTrace();
    }
}

public void initStatesList(GameContainer arg0) throws SlickException {
    this.getState(0).init(arg0, this);
    // this.getState(1).init(arg0, this);
    this.enterState(menu);
}

} }

and Menu.java (Initial game state) 和Menu.java(初始游戏状态)

public class Menu extends BasicGameState {
Image logo;

public Menu(int menu) {
}

public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException {
    logo = new Image("res/logo.png");
}

public void render(GameContainer arg0, StateBasedGame arg1, Graphics g) throws SlickException {
    g.setBackground(Color.red);
    g.drawImage(logo, 0, 0);
}

public void update(GameContainer arg0, StateBasedGame arg1, int arg2) throws SlickException {

}

public int getID() {

    return 0;
}

} }

The NullPointerException is at Menu.java:23 (g.drawImage(logo, 0, 0); I was under the impression that all of this code had been done correctly, so it surprised me when I found out otherwise. NullPointerException位于Menu.java:23(g.drawImage(logo,0,0);我觉得所有这些代码都已正确完成,因此当我发现其他代码时,这让我感到惊讶。

Side note: When fiddling with the code a bit, I found that changing 'logo' in g.drawImage(logo,0,0) for 'newImage("res/logo.png")' stopped the NullPointerException, but doesn't show the image, only the blank red background. 旁注:稍微摆弄代码时,我发现将g.drawImage(logo,0,0)中的'logo'更改为'newImage(“ res / logo.png”)'会停止NullPointerException,但不会显示图像,只有空白的红色背景。

your method 你的方法

render(GameContainer arg0, StateBasedGame arg1, Graphics g) 渲染(GameContainer arg0,StateBasedGame arg1,Graphics g)

is not getting any Graphics object, that's why it is giving NullPointException when you are calling any method over g because the variable it is assigned a null value. 没有获得任何Graphics对象,这就是为什么当您通过g调用任何方法时,它会给出NullPointException的原因,因为该变量被分配了一个空值。

find out where this method is called and see if the arguments passed are correct. 找出在哪里调用此方法,并查看传递的参数是否正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM