0
我正在努力讓我的slick2d遊戲呈現,但container.getGraphics()返回null,我得到一個空指針異常。我查了一下,這是的getGraphics(),這是返回null使用:Slick2D getGraphics()返回null,發生空指針異常
if (container.getGraphics()==null) return;
這種固定的NPE,但那麼當然我無法呈現任何內容。
堆棧跟蹤:
Tue Sep 02 21:42:19 MDT 2014 INFO:Slick Build #237
Exception in thread "Thread-1" java.lang.NullPointerException
at com.nonuniversal.client.MenuState.render(MenuState.java:17)
at org.newdawn.slick.state.StateBasedGame.render(StateBasedGame.java:199)
at com.nonuniversal.client.Game.run(Game.java:33)
at java.lang.Thread.run(Unknown Source)
請注意LunatopiaClient需要用戶名參數跑的時候......
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.SlickException;
public class LunatopiaClient{
private String username;
AppGameContainer container;
Game game;
public LunatopiaClient(String username) {
this.username = username;
}
public static void main(String args[]) {
if (args.length!=1) {
System.out.println("Usage: java -jar <filename.jar> <username>");
return;
} else {
LunatopiaClient lunatopiaClient = new LunatopiaClient(args[0]);
lunatopiaClient.init();
}
}
public void init() {
try {
game = new Game("");
container = new AppGameContainer(game);
container.setFullscreen(true);
game.init(container);
game.init();
} catch (SlickException e) {
e.printStackTrace();
}
}
public Game getGame() {
return game;
}
public String getUsername() {
return username;
}
}
類遊戲
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
public class Game extends StateBasedGame implements Runnable{
public static final int menuState = 0;
public static final int gameState = 1;
private boolean running;
private AppGameContainer container;
Thread game;
public Game(String name) {
super(name);
}
public void initStatesList(GameContainer container) throws SlickException {
this.container = (AppGameContainer) container;
addState(new MenuState());
addState(new GameState());
}
public void init() throws SlickException {
enterState(menuState);
game = new Thread(this);
game.start();
}
public void run() {
running = true;
while (running) {
try {
update(container, 0);
render(container, container.getGraphics());
} catch (SlickException e) {
e.printStackTrace();
}
}
}
}
類MenuState
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class MenuState extends BasicGameState{
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
}
public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
g.drawString("Hello World", 0, 0);
}
public void update(GameContainer container, StateBasedGame game, int arg)
throws SlickException {
}
public int getID() {
return 0;
}
}
編輯:拼寫
嘿感謝您的答案,我結束了計算出來,並順利滾動! – 2014-09-06 01:42:27