2013-07-28 54 views
6

我下面這個教程的Java Swing遊戲:http://zetcode.com/tutorials/javagamestutorial/movingsprites/Java Swing ImageIcon,在哪裏放置圖像?

此時:

ImageIcon ii = new ImageIcon(this.getClass().getResource()); 
image = ii.getImage(); 

我只是不知道我有什麼樣的路徑寫在哪裏,我要救我的圖片(哪個目錄)。

你能幫我嗎?你會舉一個例子嗎?

+0

我從zetcode中學到了很多初學Java。當你有機會的時候,你應該在YouTube上看看這個播放列表:http://youtube.com/playlist?list=PL87AA2306844063D2這也幫了我很多。 – Steven

+0

請參閱[tag:embedded-resource]&[info](http://stackoverflow.com/tags/embedded-resource/info)。 – trashgod

+0

[Eclipse中的Java:我可以在哪裏將文件放在我想要使用getResource加載的文件系統上? (例如ImageIcon的圖像)](http://stackoverflow.com/questions/270197/java-in-eclipse-where-do-i-put-files-on-the-filesystem-that-i-want-to -load-usin) – Barett

回答

0
new ImageIcon(this.getClass().getResource()); 

這意味着圖像存在於基礎類文件存在的目錄中。所以,你應該將你的圖像保存在當前java文件的類文件所在的目錄中。

12

在您的src文件夾中,創建一個名爲「images」或「files」的文件夾,然後將圖像放在那裏。

然後用這個:

ImageIcon(this.getClass().getResource("/images/filename.png")); 

如果不行,試試這個:

ImageIcon(this.getClass().getResource("images/filename.png")); 
+0

1)請使用代碼格式化代碼,輸入/輸出和結構化文檔,如HTML或XML。爲此,請選擇樣本並單擊郵件發佈/編輯表單上方的「{}」按鈕。 2)我會推薦上面看到的第一種形式。第二種形式搜索相對於類本身的包的資源。因此,如果Java源文件以'package our.code'開始;'它將在'/ our/code/images/filename.png'中查找圖像。 –

0

代碼中已有錯誤

ImageIcon ii = new ImageIcon(this.getClass().getResource()); image = 
ii.getImage(); 

你已經命名爲ImageIcon ii,所以你需要命名圖像現在可能是iii 然後,你在src中創建一個圖像目錄,並且你把你的pic放在那裏,就像sample.png一樣,代碼將會是

ImageIcon ii = new 
ImageIcon(getClass().getResource("/src/image/sample.png")); image iii= 
ii.getImage();