2017-05-27 120 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