0

In my program, I'm trying to set x and y values to game.getWidth() so that I can access those variables elsewhere. The issue is that when I run the program those variable declarations throw a NullPointerException. I'm not sure exactly why these are causing an error. Is there a way I can fix it?

package data;

import java.awt.Color;
import java.awt.Graphics2D;

public class Star {

private float mass;


public Star(Game game) {
    this.game = game;
}
private Game game;

//These variables cause the NullPointerException

private int x = game.getWidth() / 2;
private int y = game.getHeight() / 2;



public void paint(Graphics2D g) {
    g.setColor(Color.WHITE);
    g.fillOval(x, y, 12, 12);
    g.setColor(Color.BLACK);
}


public float getMass() {
    return mass;
}


public void setMass(float mass) {
    this.mass = mass;
}


public int getX() {
    return x;
}


public void setX(int x) {
    this.x = x;
}


public int getY() {
    return y;
}


public void setY(int y) {
    this.y = y;
}

}
TKDefender
  • 41
  • 6
  • Hint: `private Game game;` is the same as `private Game game = null;` – OneCricketeer Apr 29 '16 at 16:12
  • So what would I set it to so it won't be set to null? – TKDefender Apr 30 '16 at 16:42
  • You need to initialize x and y in the constructor instead of outside of it, where the Game is null – OneCricketeer Apr 30 '16 at 16:46
  • I've now moved the initialization of the x and y variables into the Star constructor, but now when I run the program the star is drawn at 0,0. Why is the `g.fillOval(x, y, 12, 12);` being called before x and y are initialized. – TKDefender Apr 30 '16 at 20:48
  • x and y are initialized to 0, and that would depend on your Game class. If you want to ask about that then, please post another question since no one can answer while this one is closed – OneCricketeer Apr 30 '16 at 21:09

0 Answers0