为什么我的代码会产生错误?

时间:2013-03-29 01:44:52

标签: java classloader inputstream

* A simple panel for testing various parts of our game.
 * This is not part of the game.  It's just for testing.
 */
package game;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

/**
  * A simple panel for testing various parts of our game.
  * This is not part of the game.  It's just for testing.
  */
public class TestPanel extends JPanel
{
    private static final long serialVersionUID = 1L;  // Ignore this - It's just to get rid of a warning.

    // Instance variable(s).

    private Image backdrop;

    /**
     * Constructor - loads a background image
     */
    public TestPanel ()
    {
        try
        {
             ClassLoader myLoader = this.getClass().getClassLoader();
             InputStream imageStream = myLoader.getResourceAsStream("resources/path_1.jpg");
             backdrop = ImageIO.read(imageStream);

             // You will uncomment these lines when you need to read a text file.

              InputStream pointStream = myLoader.getResourceAsStream("resources/   path_1.txt");
              Scanner s = new Scanner (pointStream);
        }
        catch (IOException e)
        {
            System.out.println ("Could not load: " + e);
        }
    }

    /**
     * This paint meethod draws the background image anchored
     * in the upper-left corner of the panel.  
     */
    public void paintComponent (Graphics g)
    {
        g.drawImage(backdrop, 0, 0, null);        
    }

    /* Override the functions that report this panel's size
     * to its enclosing container. */

    public Dimension getMinimumSize()
    {
        return new Dimension (600, 600);
    }

    public Dimension getMaximumSize()
    {
        return getMinimumSize();
    }

    public Dimension getPreferredSize()
    {
        return getMinimumSize();
    }
}

此代码旨在实现我正在为Java课程工作的视频游戏任务。该类仅用于测试我们的代码。在分配方向上,我被告知要在try块中放置代码,如上所示。显然,代码应该打开我工作区中文件夹中的JPEG图像。但是,当我尝试代码时,它只声明:

Exception in thread "main" java.lang.NullPointerException   at
 java.io.Reader.<init>(Unknown Source)  at
 java.io.InputStreamReader.<init>(Unknown Source)   at
 java.util.Scanner.<init>(Unknown Source)   at
 game.TestPanel.<init>(TestPanel.java:43)   at
 game.TestApplication.main(TestApplication.java:24)

我不完全清楚inputStream和classLoaders的作用。所以,如果你有任何基本信息,那就太好了。另外,我知道构造函数方法下面的其他方法没有代码。我的任务指示没有说明我应该在这些方法中输入什么。

enter code here
enter code here

1 个答案:

答案 0 :(得分:0)

有很多现有的SO问题解释了getResourceAsStream在各种情况下返回null的原因; e.g。

它们都归结为一个根本原因:类加载器找不到你告诉它找到的资源。 javadoc说如果类加载器找不到请求的资源,它将返回null而不是抛出异常。

这可能由于各种原因而发生。常见的包括:

  • 资源不存在,
  • 资源不在类路径上(例如,它是文件系统中的文件),
  • 它确实存在于类路径中,但您使用了错误的路径字符串,或者
  • 您使用了相对路径字符串,但您正在解析它的上下文不正确。
相关问题