2012-10-22 59 views
5

我想添加一個圖像到一個框架,但它似乎不工作。 ImageIcon從指定文件創建的圖像。圖像文件位於java文件存在的seam目錄中。如何將ImageIcon添加到JFrame?

import java.awt.BorderLayout; 

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

    public class image { 

     public static void main(String args[]) 
     { 
      TimeFrame frame = new TimeFrame(); 
     } 
    } 

    class TimeFrame extends JFrame 
    { 
     //Image icon = Toolkit.getDefaultToolkit().getImage("me.jpg"); 
     ImageIcon icon = new ImageIcon("me.jpg"); 
     JLabel label = new JLabel(icon); 
     public TimeFrame(){ 
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      setTitle("My Frame"); 
      setSize(500,400); 
      //this.setIconImage(icon); 
      add(label,BorderLayout.CENTER); 
      setVisible(true); 
     } 


    } 
+0

請看看如何[圖片添加到項目(http://stackoverflow.com/a/9866659/1057230 )和這[回答](http://stackoverflow.com/a/11372350/1057230)更多的澄清,如果你手動(沒有IDE)。 –

回答

5

如果你的圖標是TimeFrame的java文件旁邊,你應該使用

java.net.URL imgUrl = getClass().getResource("me.jpg"); 
ImageIcon icon = new ImageIcon(imgUrl); 

java.net.URL imgUrl = TimeFrame.class.getResource("me.jpg"); 
ImageIcon icon = new ImageIcon(imgUrl); 

你(可能)目前正在尋找它在你的工作目錄,你可以通過輸出

System.out.println(System.getProperty("user.dir")); 
+0

正如文檔所述getResource(...)查找具有給定名稱的資源。如果沒有發現這個名字的資源,這個方法返回null ...但我仍然不確定爲什麼它沒有工作過...我用這個,它工作得很好:Image image = ImageIO.read(new File(「 SydneyOperaHouse.jpg「)); – Bernard

4

你會嘗試這個嗎?

ImageIcon ImageIcon = new ImageIcon("me.jpg"); 
    Image Image = ImageIcon.getImage(); 
    this.setIconImage(Image); 
+0

Oct 23 00:24:38 MacBook-Pro.local java [592] :CGContextGetCTM:invalid context 0x0 Oct 23 00:24:38 MacBook-Pro.local java [592] :CGContextSetBaseCTM:invalid context 0x0 十月23 00:24:38 MacBook-Pro.local java [592] :CGContextGetCTM:invalid context 0x0 Oct 23 00:24:38 MacBook-Pro.local java [592] :CGContextSetBaseCTM:invalid context 0x0 – Bernard

+0

這裏是錯誤我現在得到了! – Bernard

1

只需更改目錄「的src/me.jpg」