简体   繁体   English

为什么Java突然在图像上返回空指针异常?

[英]Why does Java return null pointer exception on image all of a sudden?

I have been trying to create a resizable image by drawing BufferedImage on a panel and redrawing it whenever componentResized happened. 我一直在尝试通过在面板上绘制BufferedImage来创建可调整大小的图像,并在componentResize发生时重新绘制它。 However, despite the image loading fine in earlier versions (which either didn't resize at all or didn't do it properly) now Java claims the image isn't there. 但是,尽管在早期版本中图像加载良好(要么根本没有调整大小,要么没有正确执行),现在Java声称图像不存在。 The code is as follows 代码如下

    public class Image extends JPanel{
    BufferedImage img=null;

    public Image{
    try {
        img = ImageIO.read(new File("Untitled.png"));
    }
    catch (IOException e) {
    }
    Dimension d=getSize();
    Graphics g=getGraphics();
    g.drawImage(img, 0, 0, d.width, d.height, null);

even without the component listener, it returns NullPointerException on drawImage. 即使没有组件侦听器,它也会在drawImage上返回NullPointerException。 But I know the image isn't null, since it worked previously, which leads me to thinking there's something wrong with the code here 但是我知道图像不是空的,因为它以前可以工作,这使我想到这里的代码有问题

If something goes wrong in here: img = ImageIO.read(new File("Untitled.png")); 如果此处出现问题: img = ImageIO.read(new File("Untitled.png")); Then you are drawing on a null reference object here: 然后,您将在此处绘制空参考对象:

g.drawImage(img, 0, 0, d.width, d.height, null);

That is the reason of the NPE 这就是NPE的原因

This is due to that the Graphics object g may be null. 这是由于Graphics对象g可能为null。 Graphics g = getGraphics(); 图形g = getGraphics();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM