2015-05-23 29 views
0

我想知道有沒有人可以幫忙?我一直在開發一個Java應用程序,它在jframe上顯示來自磁盤的圖像。 使用NetBeans我已經創建了一個java包稱爲圖像我的項目內存儲的圖像在該包。首先是我應該這樣做的方式如果我希望他們隨應用程序一起發貨?netbeans中的Java,從java包中讀取映像文件

我有以下函數讀取圖像:

Image readImg(String file) 
    { 
     Image image = null; 
     try { 
      File imgFile = new File(file); 
      image = ImageIO.read(imgFile); 

     } catch (IOException e) { 
      // System.out.println("Can not Display Image"); 
      e.printStackTrace(); 
     } 
     if (image != null){  
     return image; 
    } else{ 
     return null; 
     } 
    } 

我的問題就來了,我不能制定出相對文件路徑傳遞給函數。我有要顯示的圖像調用它像這樣:

Image headerImg = readImg("C:\\Users\\[email protected]\\Documents\\NetBeansProjects\\GiftAidApp\\src\\images\\galogo.png"); 

顯然,這將徹底崩潰,如果應用程序是任何其他設備上運行。任何人都可以給我一個提醒,讓這個代碼可移植?

非常感謝

+0

使用getResources方法 –

+0

對不起Thusitha我不明白的我注意哪些類的ImageIO似乎並不具有該名稱的方法getResources方法? – danparker

回答

0

因爲它是你想添加的圖像,它可能是最好使用ImageIcon而不是Image一個JFrame

試試這個:

ImageIcon image = new ImageIcon("images/galogo.png"); 
JLabel imageLabel = new JLabel(image); 
frame.add(imageLabel); 

這應該使應用程序便攜,以及如果你包括你和你的項目一起images文件夾。