I am not able to understand why is it not working?
I've got my methods class:
package particles;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
public class Methods {
Graphics g;
public void showhud(){
g.setColor(Color.white);
g.drawString("Screen: Game", 675, 10);
g.drawString("Version: 1.0", 675, 25);
}
}
But when i try to implement showhud() in my other class, it doesn't work!
This is how im using it:
package particles;
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;
import particles.Methods;
public class Game extends BasicGameState {
Methods m;
public void init(GameContainer container, StateBasedGame game) throws SlickException {
}
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
m.showhud();
}
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
}
public int getID() {
return 0;
}
}
The error i get is:
Tue Jan 01 17:19:36 NZDT 2013 ERROR:null
java.lang.NullPointerException
at particles.Game.render(Game.java:18)
at org.newdawn.slick.state.StateBasedGame.render(StateBasedGame.java:207)
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:703)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:456)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:361)
at particles.Main.main(Main.java:23)
You haven't initialized m
- it's (still) null
, so when you execute
m.showhud();
you get a NPE because m
is null
.
You must assign an instance of Methods
to the variable m
You never assign a reference to g
. In other words, you don't have a g = ...
anywhere in your code. As such, when your Methods
class is instantiated, g
is initialised to the default value, which is null
.
you havent initialised the Methods m
object
by your code, i believe int()
method should have initialised the m object
You may need to instantiate both class members references, g and m . Currently, both references are pointing to nothing. They must point to Graphics and Methods objects respectively.
If possible, add a constructor to Methods class that will take care of initializing g .
If init() is the start of Game's (your class) lifecycle, then initialize m in this state/block.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.