Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


    }
like image 992
Bernard Avatar asked Oct 22 '12 12:10

Bernard


People also ask

How do I add a JFrame to a JFrame?

You can't put one JFrame inside another. Change your design so that the Game window content is on a JPanel and the Menu is on another JPanel .

How do you add an image to an icon in Java?

To add icon to a button, use the Icon class, which will allow you to add an image to the button. Icon icon = new ImageIcon("E:\editicon. PNG"); JButton button7 = new JButton(icon);


2 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"));
like image 96
predi Avatar answered Sep 22 '22 02:09

predi


Will u try this one?

 ImageIcon ImageIcon = new ImageIcon("me.jpg");
    Image Image = ImageIcon.getImage();
    this.setIconImage(Image);
like image 23
DRastislav Avatar answered Sep 21 '22 02:09

DRastislav