空指针错误?

时间:2012-04-13 20:55:00

标签: java nullpointerexception dialog

我正在制作一个游戏,我有几个不同的课程,因为我不喜欢把所有东西都放在一个。我有一个GameView类和一个玩家类。问题是我在GameView的玩家类中调用了一个方法。但它给我一个空指针错误。以下是我的代码:

GameVie课程:

Panel p2 = new Panel();
p2.setLayout(new BorderLayout());
JLabel player1Lbl = new JLabel("Player 1");
p2.add(player1Lbl, BorderLayout.WEST);
player.enterNameP1(); //Having an error here.
player1Lbl.setText(player.enterNameP1());

球员类:

public class Players
{
    //storing the player 1 name
    private String p1name;
    //storing the player 2 name
    private String p2name;

    /**
     * Constructor for objects of class Players
     */
    public Players()
    {
        this.p1name = p1name;
        this.p2name = p2name;
    }

    /**
     *Enter the player 1 name in a dialog box
     */
    public String enterNameP1() //It was public void before but it wasnt accepting a void method in the gameView so I changed it to String
    {
        this.p1name = JOptionPane.showInputDialog("Please enter player 1 name","Specify name");
        return p1name;
    }

3 个答案:

答案 0 :(得分:3)

你应该首先初始化玩家.....?

Players player = new Players(); 

答案 1 :(得分:3)

您拨打电话时,您的播放器未初始化:

player.enterNameP1(); //Having an error here.

要解决此问题,您必须确保引用player实际指向Player的实际实例。这应该通过在代码中的逻辑位置添加:

来完成
player = new Players();

这就是你得到NullPointerException的原因。从特定对象调用方法时,必须初始化该对象(这意味着指针player指向类Players的实际实例)。

答案 2 :(得分:1)

您没有实例化播放器 因此它是 null 导致NPE