在Java中获取NullPointerException

Pat*_*ham 0 java nullpointerexception

我写了一个上周运行良好的扫雷游戏,但现在当我尝试运行它时,我得到一个NullPointerException,我没有更改代码.

有一件事可能是原因:我在2天前在我的笔记本电脑上安装了Ubuntu,我试图将我的用户文件夹从Windows复制到我的Ubuntu桌面.我愚蠢地使用"移动到这里"选项,因为我认为这将复制文件夹(没有任何复制选项).但是当我重新登录Windows时,就好像我是一个新用户.所以我将该文件夹从我的Ubuntu桌面复制回Windows,幸运的是我的所有文件都恢复了.

这是我的代码.它确实说不推荐使用MinesweeperBoard.show()(该类扩展了JFrame),但是board = new MinesweeperBoard(9, 9, 10);即使我之前声明了板,也会发生NullPointerException .

public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.println("Do you want to play beginner (b), intermediate (i), or EXPERT (e)?");
    String input = in.next();
    MinesweeperBoard board;

    if (input.equals("b"))
        board = new MinesweeperBoard(9, 9, 10);
    else if (input.equals("i"))
        board = new MinesweeperBoard(16, 16, 40);
    else if (input.equals("e"))
        board = new MinesweeperBoard(30, 16, 99);
    else
        board = new MinesweeperBoard(30, 30, 100);

    board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    board.show();
}
Run Code Online (Sandbox Code Playgroud)

在堆栈跟踪中,它指向另一个类中的这行代码: icons[0] = new ImageIcon(this.getClass().getClassLoader().getResource("0.gif"));

之后的堆栈跟踪线是 at javax.swing.ImageIcon.<init>(Unknown Source)

我尝试构建所有并清理,但做那些没有解决任何问题.

编辑 整个堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at MBox.<init>(MBox.java:25)
at MinesweeperBoard.<init>(MinesweeperBoard.java:50)
at MinesweeperGame.main(MinesweeperGame.java:16)
Run Code Online (Sandbox Code Playgroud)

这是来自MinesweeperBoard:

for (int i = 0; i < numRows; i++)
    {
        for (int j = 0; j < numCols; j++)
        {
            boxes[i][j] = new MBox(i, j); //Line 50
            boxes[i][j].setBounds(i * SIZE + 5, j * SIZE + 65, SIZE, SIZE);
            boxes[i][j].putSelfInBoard(this);
            cont.add(boxes[i][j]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是来自MBox:

    icons = new ImageIcon[12];
    icons[0] = new ImageIcon(this.getClass().getClassLoader().getResource("0.gif")); //Line 25
    icons[1] = new ImageIcon(this.getClass().getClassLoader().getResource("1.gif"));
    icons[2] = new ImageIcon(this.getClass().getClassLoader().getResource("2.gif"));
    ...
Run Code Online (Sandbox Code Playgroud)

Jef*_*rey 6

这NullPointerException可能是因为this.getClass().getClassLoader().getResource("0.gif")正在返回null.


Jon*_*eet 5

听起来像文件"0.gif"不在你的jar文件中(或任何地方),因此getClass().getClassLoader().getResource("0.gif")返回null.然后将其传递给ImageIcon构造函数,构造函数抛出异常.