2014-12-03 127 views
0

我想爲這個遊戲加載一個背景圖片,該文件與類文件位於同一個文件夾中,並且只有一個文件夾。我搜索了不同的方式來引用文件,並且都失敗了。這是拋出的錯誤:加載文件時發生NullPointerException錯誤

Exception in thread "main" java.lang.NullPointerException 
    at javax.swing.ImageIcon.<init>(Unknown Source) 
    at ThrustR.<init>(ThrustR.java:28) 
    at ThrustR.main(ThrustR.java:35) 

這裏是代碼:

public class ThrustR extends JFrame 
{ 
    public String path; 
    public File file; 
    public BufferedImage image; 

    public void setValues() throws IOException 
    { 
     path = "CityRed.jpg"; 
     file = new File(path); 
     image = ImageIO.read(file); 
    } 

    public ThrustR(String title) 
    { 
     super(title); 

     JLabel back = new JLabel(new ImageIcon(image)); 

    } 

    public static void main(String[] args) 
    { 
     // Main Window 
     ThrustR frame = new ThrustR("ThrustR"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(720,480); 
     frame.setVisible(true); 

    } 
} 
+0

路徑= 「CityRed.jpg」;不會返回HDD,Java包或BufferedImage中的有效路徑,然後返回NullPointerException的原因,以獲取有關Java包的Oracle教程的更多信息 – mKorbel 2014-12-03 17:15:44

回答

0

嘗試:

getClass().getResource("/CityRed.jpg") 
0

你是不是從任何地方調用你setValues()方法。

我可以做什麼,當程序開始執行它去main()方法在其中創建您的ThrustR frame = new ThrustR("ThrustR");類的對象,它會調用它的構造函數,這是

public ThrustR(String title){ 
    super(title); 
    JLabel back = new JLabel(new ImageIcon(image)); 
} 

而且在這是您創建ImageIcon的另一個對象,即new ImageIcon(image),此時image將爲空。由於setValues()目前還沒有被調用,並且默認public BufferedImage image;將爲空。

0

您還沒有調用setvalues()方法。我已經對你的代碼做了一些改變,它可以爲你工作,你可以嘗試。

public class ThrustR extends JFrame { 
 
// public String path; 
 
// public File file; 
 
// public BufferedImage image; 
 

 
// public void setValues() 
 
// { 
 
    // path = "/CityRed.jpg"; 
 
    // file = new File(path); 
 
    //image = ImageIO.read(file); 
 
// } 
 
    public ThrustR(String title) throws IOException { 
 
     super(title); 
 
     String path = "CityRed.jpg"; 
 
     File file = new File(path); 
 
     BufferedImage image = ImageIO.read(file); 
 
     JLabel back = new JLabel(new ImageIcon(image)); 
 
     this.add(back); 
 

 
    } 
 

 
    public static void main(String[] args) throws IOException { 
 
     // Main Window 
 
     ThrustR frame = new ThrustR("ThrustR"); 
 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
     frame.setSize(720, 480); 
 
     frame.setVisible(true); 
 

 
    } 
 
}

相關問題