2012-06-28 71 views
8

我想用Java製作一個非常基本的遊戲,但我在JFrame上顯示圖像時遇到了問題。它在過去爲我工作,現在不是,我看不出我做錯了什麼。Java將ImageIcon添加到JLabel

我已經嘗試打印當前的工作目錄,並更改我的圖像匹配的位置。這很可能是因爲我的(檔案尋找器或文件讀取器等)沒有問題,但我無法正確地將它(ImageIcon)添加到JLabelJFrame,從而無法獲取圖像。

這是我的代碼...

JFrame frame = new JFrame("no image"); 
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png"); 
JLabel imagelabel = new JLabel(image); 
frame.add(imagelabel); 

JFrame已經setVisible(true)pack()

有人可以幫助我瞭解什麼是錯的。

+0

請看看這個例子中,[如何增加圖象到你的項目](http://stackoverflow.com/questions/9864267/load-icon-image-exception/9866659#9866659)或請按照這些[步驟](http:// ga gandeepbali.uk.to/gaganisonline/webpages/makejareclipse.html) –

+0

我看了那些例子,他們沒有幫助 – user1486826

+0

只需將你的圖像放在你的.class文件旁邊,並像這樣使用ImageIcon image = new ImageIcon(getClass( ).getResource( 「yourImage.extension」));.該鏈接必須有效,因爲這是將圖片放入項目中的正確方法。我希望你已經完成了所有提到的步驟! –

回答

12

你的問題就在這裏:

ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png"); 
    JLabel imagelabel = new JLabel(character); 

您創建一個ImageIcon 「形象」,但你創建一個 「字」 您的JLabel。

它應該是:

JLabel imagelabel = new JLabel(image); 
+0

對不起,在我的實際代碼中他們是一樣的,我忘了用圖像替換字符。 – user1486826

3

嘗試,

ImageIcon image = new ImageIcon("c:\\path\\image.png"); 
imagelabel = new JLabel(character, image, JLabel.CENTER); 
frame.add(imagelabel); 

在教程看看 - How to use Icons

+0

我已經多次看過這個教程,我沒有看到我做錯了什麼。 – user1486826

-1
import javax.awt.*; 
import java.awt.*; 
import java.awt.event*; 

//class name image 
class image { 
    image() 
    //constructor { 
     Frame f=new Frame("Image"); 
     //Frame 
     f.setSize(500,500); 
     f.setVisible(true); 
     Panel p =new Panel(); 
     //Panel 
     f.add(p); 
     p.addLayout(null); 
     ImageIcon ii=new ImageIcon("set your image path"); 
     //ImageIcon is used to image Display . 
     Label l =new Label(ii); 
     p.add(ii); 
     p.setBounds(set you bounds); 
     //Like that(20,20,500,40); 
    } 

    public static void main(String [] args) { 
     image obj = new 
    } 
} 
+2

請爲你的代碼添加一些解釋,並說明爲什麼OP需要你的代碼;)。 –