How to add an ImageIcon to a JFrame?

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

3 Answers

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"));
1

Will u try this one?

 ImageIcon ImageIcon = new ImageIcon("me.jpg"); Image Image = ImageIcon.getImage(); this.setIconImage(Image);
1

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like