【问题标题】:Why does this code throw a java.lang.NullPointerException?为什么这段代码会抛出 java.lang.NullPointerException?
【发布时间】:2010-01-08 18:33:26
【问题描述】:

我找到了一个源代码,我将它添加到我的框架中只是为了测试它使用 Java2D。 但它是一个例外。我不明白为什么。

我的班级:

package ClientGUI;




import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;

/**
 *
 * @author ICC
 */

public class SignInFrame extends javax.swing.JFrame implements Runnable {

private static int iw,  ih,  iw2,  ih2;
private static Image img;
private static final int FORWARD = 0;
private static final int BACK = 1;

// the points of the curve
private Point2D pts[];

// initializes direction of movement forward, or left-to-right
private int direction = FORWARD;
private int pNum;
private int x,  y;
private Thread thread;
private BufferedImage bimg;

/** Creates new form SignInFrame */
public SignInFrame() {
    initComponents();
    img = getToolkit().getImage(Image.class.getResource("Yahoo-Messanger.jpg"));
    try {
        MediaTracker tracker = new MediaTracker(this);
        tracker.addImage(img, 0);
        tracker.waitForID(0);
    } catch (Exception e) {
    }
    iw = img.getWidth(this);
    ih = img.getHeight(this);
    iw2 = iw / 2;
    ih2 = ih / 2;

}

public void reset(int w, int h) {
    pNum = 0;
    direction = FORWARD;

    // initializes the cubic curve
    CubicCurve2D cc = new CubicCurve2D.Float(
            w * .2f, h * .5f, w * .4f, 0, w * .6f, h, w * .8f, h * .5f);

    // creates an iterator to define the boundary of the flattened curve
    PathIterator pi = cc.getPathIterator(null, 0.1);
    Point2D tmp[] = new Point2D[200];
    int i = 0;

    // while pi is iterating the curve, adds points to tmp array
    while (!pi.isDone()) {
        float[] coords = new float[6];
        switch (pi.currentSegment(coords)) {
            case PathIterator.SEG_MOVETO:
            case PathIterator.SEG_LINETO:
                tmp[i] = new Point2D.Float(coords[0], coords[1]);
        }
        i++;
        pi.next();
    }
    pts = new Point2D[i];

    // copies points from tmp to pts
    System.arraycopy(tmp, 0, pts, 0, i);
}

public void step(int w, int h) {
    if (pts == null) {
        return;
    }
    x = (int) pts[pNum].getX();
    y = (int) pts[pNum].getY();
    if (direction == FORWARD) {
        if (++pNum == pts.length) {
            direction = BACK;
        }
    }
    if (direction == BACK) {
        if (--pNum == 0) {
            direction = FORWARD;
        }
    }
}

public void drawDemo(int w, int h, Graphics2D g2) {
    g2.drawImage(img,
            0, 0, x, y,
            0, 0, iw2, ih2,
            this);
    g2.drawImage(img,
            x, 0, w, y,
            iw2, 0, iw, ih2,
            this);
    g2.drawImage(img,
            0, y, x, h,
            0, ih2, iw2, ih,
            this);
    g2.drawImage(img,
            x, y, w, h,
            iw2, ih2, iw, ih,
            this);
}

public Graphics2D createGraphics2D(int w, int h) {
    Graphics2D g2 = null;
    if (bimg == null || bimg.getWidth() != w || bimg.getHeight() != h) {
        bimg = (BufferedImage) createImage(w, h);
        reset(w, h);
    }
    g2 = bimg.createGraphics();
    g2.setBackground(getBackground());
    g2.clearRect(0, 0, w, h);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING,
            RenderingHints.VALUE_RENDER_QUALITY);
    return g2;
}

@Override
public void paint(Graphics g) {
    Dimension d = getSize();
    step(d.width, d.height);
    Graphics2D g2 = createGraphics2D(d.width, d.height);
    drawDemo(d.width, d.height, g2);
    g2.dispose();
    g.drawImage(bimg, 0, 0, this);
}

public void start() {
    thread = new Thread(this);
    thread.setPriority(Thread.MIN_PRIORITY);
    thread.start();
}

public synchronized void stop() {
    thread = null;
}

public static void main(String argv[]) {

    SignInFrame f = new SignInFrame();





    f.start();
}

public void run() {

    Thread me = Thread.currentThread();
    while (thread == me) {
        repaint();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            break;
        }
    }
    thread = null;
}}

例外:

在里面: deps-jar: 将 1 个源文件编译到 C:\Users\ICC\Documents\NetBeansProjects\YahooServer\build\classes 编译单: 单跑: 获取图像时未捕获的错误: java.lang.NullPointerException 在 sun.awt.image.URLImageSource.getConnection(URLImageSource.java:97) 在 sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:107) 在 sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240) 在 sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172) 在 sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)

【问题讨论】:

  • 所以一些未指定的代码以未指定的方式被调用并且它是错误的。由于我们看不到代码,我们无法说出原因。
  • 如果您提供堆栈跟踪或至少提供导致 NullPointer 的行,事情会变得更容易。
  • 对不起,我的网络有问题,我已经发布了。
  • 异常几乎从不返回,它们通常被抛出!巨大差距!虽然从技术上讲你可以返回一个异常,但我从未见过它在严肃的代码中完成。

标签: java nullpointerexception java-2d


【解决方案1】:

有问题的线在这里 img = getToolkit().getImage(Image.class.getResource("Yahoo-Messanger.jpg")); 确保文件存在请参阅此文档以查看有关资源加载方式的顺序 Java Doc for getResource

【讨论】:

  • Greg 突出显示的行中的“Messanger”拼写错误,这可能是它无法找到图像的原因。
【解决方案2】:
java.lang.NullPointerException
    at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:97)

我做了一个疯狂的猜测:URL 为空。您需要调试在 您自己的 代码第一次出现在堆栈跟踪中时使用的变量。我已经 explained 在您之前的一个主题中如何调试。

【讨论】:

【解决方案3】:

使用您的调试器并定义一个断点,以便您的应用程序在抛出 NPE 时停止。然后,您会找到导致问题的空引用的代码行。 (或在堆栈跟踪上打印的代码行设置断点)

如果不查看引发异常的代码部分,几乎不可能提供更详细的帮助。

编辑

这次是简单的错字?图像文件是名为Yahoo-Messanger.jpg 还是不应该是Yahoo-Messenger.jpg?可能是找不到图片。不幸的是,您的堆栈跟踪 sn-p 不包含您的类中开始出现问题的代码行。

【讨论】:

  • 遇到同样的错误,堆栈跟踪实际上并不包含一行自定义代码。您也无法自己捕获异常并缓解问题。
【解决方案4】:

我发现解决这些问题的最佳方法是一步一步来。异常指出获取图像时出错。在SignInFrame() 中,您正在尝试检索图像img = getToolkit().getImage(Image.class.getResource("Yahoo-Messanger.jpg"));

确保您正确指向图像。查看javadoc for getResource 也可能会有所帮助。

另外,我认为(我不是专家)将可能引发异常的方法放在 try-catch 中通常是个好主意。通过这种方式,您可以准确地知道抛出异常时错误发生的位置。

【讨论】:

    【解决方案5】:

    我认为当你调用 f.start() 时,它实际上会调用 run() 方法而不是你自己的 start() 方法,因为该类实现了 Runnable。

    【讨论】:

      【解决方案6】:

      这个问题已经回答了,但我建议在这一行做两个额外的改变:

          img = getToolkit().getImage(Image.class.getResource("Yahoo-Messanger.jpg"));
      

      1 - 检查返回的 URL,如果没有找到图像,它将是 null

      2 - 我认为Image.class 在这里具有误导性。使用getClass(),因为没有(明显的)理由使用 Image 类的 Classloader。

          URL url = getClass().getResource("Yahoo-Messanger.jpg");
          if (url == null) {
              // some error handling here: throw an Exception, logging, ...
          }
          img = getToolkit().getImage(url);
      

      抛出异常将是最好的解决方案恕我直言。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-18
        相关资源
        最近更新 更多