得到空指针,不知道为什么

时间:2013-12-12 16:15:48

标签: java nullpointerexception jpanel awt

我正在制作一个程序,在4 x 4网格中面朝下显示8对卡片,你需要找到要赢的对。

我已经编写了类,当我尝试运行时,我得到了一个N​​ullPointerException。但我不知道为什么。

这是错误所在的代码:

public Game(String s)
{
    super(s);
    JPanel cp = (JPanel)getContentPane();
    cp.add("North", scoreLabel);
    surface = new JPanel();
    surface.setLayout(new GridLayout(4, 4));
    cp.add("Center", surface);
    prepareCards();
    for (int x = 0; x < 16; x++)
    {
        Card temp = p.dealCard();
        System.out.println(temp);
        temp.addMouseListener(cardHandle);
        **surface.add(temp);**
    }
}
public static void main(String args[])
{
    *Game game = new Game("TEST GAME PLEASE IGNORE");*
    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.setSize(600, 400);
    game.setVisible(true);
}

下面的错误(这不是很有用)。

Exception in thread "main" java.lang.NullPointerException
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    at certClasses.Game.<init>(Game.java:39)
    at certClasses.Game.main(Game.java:44)

第39行是双星号(** **),第44行是单个星号(* *)。

我已经搜索了错误,并没有得到任何帮助(stackoverflow任务已关闭,因为大多数情况下不太可能帮助其他人)。我会尽可能将整个代码发布在pastebin上;我现在不在家,而且pastebin被阻止为“个人网络存储和备份”。

2 个答案:

答案 0 :(得分:1)

空指针异常告诉您其中一个变量为null,并且您以不恰当的方式使用它

这种情况主要发生在您尝试使用对象的方法时(例如):

// gives NPE if temp == null, because null does not have any methods
temp.addMouseListener(cardHandle);

null添加到some collections, E.g. Queue时也会出现这种情况(尽管some collections allow it):

// gives NPE if temp == null (also if surface == null) 
surface.add(temp);

要在控制台中对此进行调试,您可以在null例外发生之前打印可疑的值:

// you actually have this in your code, so you should see 'null' printed
Card temp = p.dealCard();
System.out.println(temp);
// you should also print this out since surface could possibly be the null nulprit
System.out.println(surface);

答案 1 :(得分:0)

我自己发现了这个问题。这是一个错误的错误。我试图用14张牌填充一个4乘4的网格,所以当它找到第15个时它得到一个空值。它现在运行!大多。无论如何,感谢你的帮助,你指出了我正确的方向。