将变量设置为.getWidth()方法,返回nullPointerException

时间:2016-04-29 16:05:01

标签: java

在我的程序中,我试图将x和y值设置为game.getWidth(),以便我可以在其他地方访问这些变量。问题是,当我运行程序时,这些变量声明会抛出NullPointerException。我不确定这些导致错误的确切原因。有没有办法解决它?

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;
}

}

0 个答案:

没有答案