2014-04-22 64 views
0

這裏是我的代碼:錯誤而載入圖像

import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.*; 
import javax.swing.ImageIcon; 
import javax.swing.JLabel; 
import model.Map; 


public class MyView { 

    private BufferedImage img = null; 
    private static MyPanel panel; 

    //init image 

    try{ 
     img = ImageIO.read(new File("/src/minepic/start.png")); 
    } catch (IOException e){ 
     System.out.println(e.getMessage()); 
    } 
} 

我想從src目錄加載PNG圖像,但我不知道爲什麼,這是行不通的,任何人都可以幫我嗎?

錯誤的命令「try catch」和NetBeans說「未報告的異常IOexception;必須被捕獲或聲明爲拋出」 另外,即使我之前宣佈img爲BufferedImage,但在命令「try catch」img中像沒有聲明,因爲在NetBeans中它不會變綠,仍然是黑色。

回答

0

很少有問題的代碼:

  1. 它是不完整的。大括號不匹配。
  2. 外主要方法你寫的代碼(可能的,但不推薦)
  3. 要讀取的src文件夾中的圖像(這是你的類路徑的一部分)使用下面的代碼片段:

    Inputstream is = MyView.class.getResourceAsStream("minepic/start.png"); 
    if(is==null){ 
        is = MyView.class.getClassLoader().getResourceAsStream("minepic/start.png"); 
    } 
    img = ImageIO.read(is);