6

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


    }
4

3 回答 3

5

如果你的图标在 java 文件旁边TimeFrame,你应该使用

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

或者

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

您(可能)目前正在您的工作目录中寻找它,您可以通过它输出

System.out.println(System.getProperty("user.dir"));
于 2012-10-22T13:10:39.210 回答
4

你会试试这个吗?

 ImageIcon ImageIcon = new ImageIcon("me.jpg");
    Image Image = ImageIcon.getImage();
    this.setIconImage(Image);
于 2012-10-22T13:13:38.763 回答
2

只需将目录更改为“src/me.jpg”

于 2016-01-20T13:58:10.047 回答