8

I'm trying to add an image to one frame but it seems it does not working. The image created by an ImageIcon from the specified file. The image file is in the seam directory the java file exist.

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);
        }


    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Bernard
  • 4,240
  • 18
  • 55
  • 88
  • Please have a look at How to [ADD IMAGES TO YOUR PROJECT](http://stackoverflow.com/a/9866659/1057230) and this [answer](http://stackoverflow.com/a/11372350/1057230) for more clarification, if you doing it manually (without IDE). – nIcE cOw Oct 22 '12 at 16:11

3 Answers3

7

If your icon is beside the TimeFrame java file, you should use

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

or

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

You are (probably) currently looking for it in your working directory which you can output via

System.out.println(System.getProperty("user.dir"));
predi
  • 5,528
  • 32
  • 60
  • As documentation says getResource(...) Finds a resource with a given name. This method returns null if no resource with this name is found...but still i'm not sure why it did not worked before... I used this and it worked fine : Image image = ImageIO.read(new File("SydneyOperaHouse.jpg")); – Bernard Oct 22 '12 at 13:21
4

Will u try this one?

 ImageIcon ImageIcon = new ImageIcon("me.jpg");
    Image Image = ImageIcon.getImage();
    this.setIconImage(Image);
DRastislav
  • 1,892
  • 3
  • 26
  • 40
  • 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 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 – Bernard Oct 22 '12 at 13:25
2

Simply change the directory to "src/me.jpg"