2014-02-18 37 views
2

我嘗試使用JLabel顯示圖像。這是我的項目導航: enter image description here將圖像加載到JLabel中不起作用

SettingsDialog.java我想用顯示圖像下面的代碼:

 String path = "/images/sidebar-icon-48.png"; 
     File file = new File(path); 
     Image image; 
     try { 
      image = ImageIO.read(file); 

      JLabel label = new JLabel(new ImageIcon(image)); 
      header.add(label); // header is a JPanel 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

代碼拋出一個異常:無法讀取輸入文件!

圖像的路徑是否錯誤?

+0

該文件的路徑不正確。例外情況非常明顯。 –

+2

請看看[這個答案](http://stackoverflow.com/a/9866659/1057230)對於__Eclipse__相關的部分,可能會對此有所贅述。此鏈接也可在[tag:embedded-resource] –

回答

4

不要從文件中讀取,從類路徑

image = ImageIO.read(getClass().getResource(path)); 
-or- 
image = ImageIO.read(MyClass.class.getResource(path)); 

讀取當您使用File對象,你告訴該程序從文件系統,這將使你的路徑無效閱讀。您正在使用的路徑正確,但從類路徑中讀取時,應如應該所做的那樣。

查看wiki上的embedded resource。另請參閱getResource()


UPDATE測試運行

enter image description here

package org.apache.openoffice.sidebar; 

import javax.swing.*; 

public class SomeClass { 
    public SomeClass() { 
     ImageIcon icon = new ImageIcon(
       SomeClass.class.getResource("/images/sidebar-icon-48.png")); 
     JLabel label = new JLabel(icon); 

     JFrame frame = new JFrame("Test"); 
     frame.add(label); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run() { 
       new SomeClass(); 
      } 
     }); 
    } 
} 
+0

的信息中獲得答案,但代碼無效。如果我嘗試打印getClass()。getResource(path)結果,我看到「NULL」 – MaTTP

+0

如果這個''/images/sidebar-icon-48.png''是你正在使用的文件路徑,並且上面的圖像是你的實際的文件結構,它_should_工作。我從來沒有遇到過問題。 –

+0

@MTTP看到我的**更新** –

1

「/images/sidebar-icon-48.png」 是根路徑。根據當前驅動器的不同,在Windows上將是c:\ images \ sidebar-icon-48.png或d:\ images \ sidebar-icon-48.png(java將/轉換爲\ - 不是問題)。 Linux的圖像會成爲根的孩子/images/sidebar-icon-48.png需要加載相對類或相對於有類的jar(如果你不想在jar中存儲圖像)

在大項目很高興有圖像和其他資源在罐子外面,所以罐子更小,更重要的是它很容易改變資源,而不會擺弄罐子/戰爭

因爲你似乎在爲開放式辦公添加附加功能,你必須把所有的東西都放在jar裏面,所以peeskillet的答案是正確的,但是要確保你的images文件夾已經被打包在jar裏了,解壓縮jar文件就是jar命令,或者重命名文件來壓縮和解壓縮文件。

或者檢查並修復項目設置。如何使一個罐子在日食...最新的一個具有wizard that makes an ant script或本SO

1

嘗試直接用這個:

JLabel label = new JLabel(new ImageIcon(path)); 

,並刪除這些行:

File file = new File(path); 

image = ImageIO.read(file); 

如果故障仍存在粘貼以下錯誤