2013-03-29 62 views
0
* 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和類加載器。所以,如果你有任何基本的信息,那就太好了。另外,我知道構造函數方法下的其他方法在其中沒有代碼。我的任務的方向沒有說明我應該輸入這些方法。

enter code here 
enter code here 
+3

您需要仔細觀察由TestPanel的異常消息43行顯示的代碼行。該行的內容爲空。 –

回答

1

你必須在第二個文件名有一些額外的空間:

「資源/ path_1.txt」

顯然,這是一個錯字。然後,當你用這個流調用getResourceAsStream時,由於這些額外的空間,它沒有找到你想要的文件,所以這個調用返回一個空指針,它被傳遞到掃描器,並最終導致NPE。

0

有很多現有的SO問題可以解釋爲什麼getResourceAsStream在各種情況下返回null;例如

他們都歸結爲一個根本原因:類裝載器不能找到你告訴它找到的資源。 javadoc說如果類加載器找不到請求的資源,它將返回null而不是拋出異常。

而這可能會發生各種原因。常見的包括:

  • 的資源不存在,
  • 的資源不是在類路徑中(例如,它是在文件系統中的文件),
  • 它在類路徑上存在,但您使用了錯誤的路徑字符串,或者您使用了相對路徑字符串,但您解析它的上下文不正確。
相關問題