永久获取NullPointerException并且没有代码

时间:2016-01-22 00:29:39

标签: java nullpointerexception

基本上我正在尝试加载调整图像大小以将其放在JButton上。这在今天早些时候工作,但是当我把我的驱动器带回家工作并运行程序时,我得到了java.lang.NullPointerException

我是Java的新手,请原谅我,如果我错了,但通常这实际上意味着我打电话给那些不存在的东西。无论如何,它都表明错误在第179行,即使我将代码向上或向下移动了几行。即使这行没有代码,我也会收到错误。我已将错误附近的代码包含在内,并在底部包含完整的错误消息。

谢谢!

Image play = null;
try {
    play = ImageIO.read(new File("/images/play.png"));
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
System.out.println("true");

Image pause = null;
try {
    pause = ImageIO.read(new File("/images/pause.png"));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

// The line it says the error is on.
ImageIcon playIcon = new ImageIcon(play.getScaledInstance(25, 25, Image.SCALE_DEFAULT));
ImageIcon pauseIcon = new ImageIcon(pause.getScaledInstance(25, 25, Image.SCALE_DEFAULT));

btnPause.setIcon(playIcon);
btnPause.setSelectedIcon(pauseIcon);

堆栈追踪:

java.lang.NullPointerException
at Main.<init>(Main.java:179)
at Main$1.run(Main.java:55)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

1 个答案:

答案 0 :(得分:2)

您的代码存在使用try..catch块的方式以及处理异常的问题。从您的示例中获取相关代码:

try {
    play = ImageIO.read(new File("/images/play.png"));
} catch (IOException e1) {
    e1.printStackTrace();
}
ImageIcon playIcon = new ImageIcon(play.getScaledInstance(25, 25, Image.SCALE_DEFAULT));

如果第二行(读取图像并将其分配给play)失败,则抛出异常,捕获并打印出异常。然后继续,即使play未被分配。因此,当您致电play.getScaledInstance()时,您将获得NullPointerException因为playnull

您需要做的是停止处理并返回一些失败指示。你无法继续。