1

I had written a Java program in Swing to display an image in frame. But it is not working.

Do I have to add image in package in Netbeans?

Here is my code:

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);    
    }   
}   
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Harry
  • 11
  • 5
  • 1
    Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson May 27 '17 at 08:42

1 Answers1

1

This ImageIcon i=new ImageIcon("stone.jpg"); should work if stone.jpg is stored at the project root directory.
If it it elsewhere, you need to modify the path. For example if it is under resources use ImageIcon i=new ImageIcon("resources/stone.jpg") .
To make sure the image was found you can use System.out.println(i.getIconWidth()); which will printout -1 if it wasn't.


Best practice is to use getResource as described here.

c0der
  • 18,467
  • 6
  • 33
  • 65