How to add an ImageIcon to a JFrame?
Asked Answered
A

3

9

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


    }
Apologetic answered 22/10, 2012 at 12:42 Comment(1)
Please have a look at How to ADD IMAGES TO YOUR PROJECT and this answer for more clarification, if you doing it manually (without IDE).Scheer
O
8

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"));
Oscular answered 22/10, 2012 at 13:10 Comment(1)
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"));Apologetic
D
4

Will u try this one?

 ImageIcon ImageIcon = new ImageIcon("me.jpg");
    Image Image = ImageIcon.getImage();
    this.setIconImage(Image);
Dereliction answered 22/10, 2012 at 13:13 Comment(1)
Oct 23 00:24:38 MacBook-Pro.local java[592] <Error>: CGContextGetCTM: invalid context 0x0 Oct 23 00:24:38 MacBook-Pro.local java[592] <Error>: CGContextSetBaseCTM: invalid context 0x0 Oct 23 00:24:38 MacBook-Pro.local java[592] <Error>: CGContextGetCTM: invalid context 0x0 Oct 23 00:24:38 MacBook-Pro.local java[592] <Error>: CGContextSetBaseCTM: invalid context 0x0Apologetic
C
1

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

Charpoy answered 20/1, 2016 at 13:58 Comment(1)
The srcdirectory won’t be there at runtime.Waki

© 2022 - 2024 — McMap. All rights reserved.