I have some class which creates a Ship (class Ship extends GameObject) and attempts to add it to a gameBoard.
To do this, it tells the gameFrame to add the object as follows:
public void startNewGame() {
Ship myShip = new Ship(GAME_BOARD_WIDTH / 2, GAME_BOARD_HEIGHT-1, SHIP_WIDTH,
SHIP_HEIGHT);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
gameFrame = new InvadersGameFrame();
}
});
gameFrame.addGameObject(myShip); //Problem line
gameFrame.repaint();
}
The gameFrame then calls:
GameBoard gameBoard = new GameBoard();
...
...
public void addGameObject(GameObject ob) {
gameBoard.addGameObject(ob);
}
Which in turn calls:
public class GameBoard extends JPanel implements GameData{
private JPanel gameBoard;
private List<GameObject> objects = new ArrayList<>();
public GameBoard() {
gameBoard = new JPanel();
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.black);
g.setColor(Color.RED);
for(GameObject ob : objects){
g.drawOval(ob.x, ob.y, ob.width, ob.height);
}
}
//Places object into list for drawing upon next repaint.
public void addGameObject(GameObject ob) {
objects.add(ob);
}
}
Now my problem is that I receive a Null Pointer Exception when I gameFrame.addGameObject(myShip);
The tricky thing is when I run via debugger I do not receive the NPE at all (but my objects list still seems empty).
Also, I can follow into each of these and still see myShip, so am I just referencing my GameObject (Ship) wrong?
Should my parameters for addGameObject somehow be more abstract?