我正在使用Slick 2D制作RTS游戏。我有一个构建类,它包含一个名为resources的int。我希望资源变量成为一个字符串,并渲染到我的建筑物的中心(它应该是一个矩形)。
这是我的建筑类:
package test;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;
public class BaseBuilding extends Rectangle{
private int resources;
private Graphics g;
public BaseBuilding(float x, float y, float width, float height) {
super(x, y, width, height);
resources = 0;
g = new Graphics();
} // end constructor
public void render(){
g.drawString("bro wat", resources, resources);
g.setColor(Color.gray);
g.fill(this);
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
} // end update
public int getResources(){
return resources;
} // end getResources
public void addResources(int mulla){
resources += mulla;
if (resources < 0)
resources = 0;
} // end addResources
public void createBasicUnit(){
// create a BasicUnit object in a randomly, valid position close to this object
// TODO
} // end createBasicUnit
} // end class def
到目前为止,我的所有州都在工作,我得到了适当的矩形。我的带有正确参数的g.drawString(str,float,float)代码将在我的GameState类(未显示)的render函数中工作,但它在我的BaseBuilding类中给出了这个错误:
java.lang.NullPointerException
at org.newdawn.slick.Graphics.drawString(Graphics.java:1366)
at test.BaseBuilding.render(BaseBuilding.java:19)
at test.GameState.render(GameState.java:34)
at org.newdawn.slick.state.StateBasedGame.render(StateBasedGame.java:199)
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:688)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at test.StateBaseGame.main(StateBaseGame.java:22)
Sat Apr 18 03:18:55 EDT 2015 ERROR:Game.render() failure - check the game code.
org.newdawn.slick.SlickException: Game.render() failure - check the game code.
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:691)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at test.StateBaseGame.main(StateBaseGame.java:22)
所以我挖了一下,发现这条线路引起了我的问题:
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
无法在互联网上找到它;如果可以请帮助谢谢。
答案 0 :(得分:2)
在查看Slick源代码后,您的问题来自 Graphics 类中的 font 变量,该变量为null。
您使用默认构造函数实例化Graphics,该构造函数不提供font变量的默认值。而另一个,正如doc所说,只有容器应该实例化Graphics。
所以,你永远不应该实例化Graphics,而只是从GameContainer( getGraphics )中检索everywhere,或者你也可以 g 来自游戏类的 render 方法(Game,BasicGame,BasicGameState,StateBasedGame,具体取决于您使用的内容......)。
为了简单起见,只需通过render方法传递Graphics对象:
public void render(Graphics g){
g.drawString("bro wat", resources, resources);
g.setColor(Color.gray);
g.fill(this);
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
} // end update
在你的游戏中:
render(GameContainer container, Graphics g) {
myBaseBuilding.render(g);
}