2017-05-27 157 views
1

我在Swing中編寫了一個Java程序來在框架中顯示圖像。但它不起作用。如何在框架中顯示圖像?

我必須在NetBeans中添加圖像軟件包?

這裏是我的代碼:

import java.awt.*; 
import javax.swing.*; 
import javax.swing.border.*; 
//import java.awt.Image.*; 
public class Images extends JFrame implements ActionListener {   
    JButton b; 
    JLabel l; 
    Images() 
    { 
     Container c=getContentPane(); 
     c.setLayout(new FlowLayout()); 
     ImageIcon i=new ImageIcon("stone.jpg"); 
     b=new JButton("Click Me",i); 
     b.setBackground(Color.yellow); 
     b.setForeground(Color.red); 
     b.setFont(new Font("Arial",Font.BOLD,30)); 
     Border bd=BorderFactory.createBevelBorder(BevelBorder.RAISED);  
     b.setBorder(bd); 
     b.setToolTipText("Buttons"); 
     b.setMnemonic('C'); 
     c.add(b);  
    b.addActionListener(this);  
    l=new JLabel();  
    c.add(l);  
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    }  
    public void actionPerformed(ActionEvent ae)  
    { 
     ImageIcon i=new ImageIcon("stone.jpg"); 
     l.setIcon(i); 
    } 

public static void main(String args[])  
    { 
     Images d=new Images();  
     d.setTitle("Hello");  
     d.setSize(700,700);  
     d.setVisible(true);  
    } 
} 
+1

應用程序資源在部署時將成爲嵌入式資源,所以現在開始訪問它們是明智的做法。 [tag:embedded-resource]必須通過URL而不是文件訪問。請參閱[信息。頁面爲嵌入式資源](http://stackoverflow.com/tags/embedded-resource/info)如何形成的URL。 –

回答

1

如果stone.jpg存儲在項目的根目錄這ImageIcon i=new ImageIcon("stone.jpg");應該工作。
如果它在別處,則需要修改路徑。 例如,如果它在資源下使用ImageIcon i=new ImageIcon("resources/stone.jpg")
爲了確保找到圖像,您可以使用System.out.println(i.getIconWidth());,如果不是,將會打印-1。


最佳做法是使用getResource,如here所述。

+0

感謝您的幫助 – Harry

+0

它解決了問題嗎? – c0der

+0

是的,它幫助我很多。現在我的圖像顯示在框架中。 – Harry