如何将 ImageIcon 添加到 JFrame?

2022-01-24 00:00:00 java swing jlabel imageicon jframe

我正在尝试将图像添加到一帧,但它似乎不起作用.ImageIcon 从指定文件创建的图像.图片文件在java文件存在的seam目录下.

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


    }

推荐答案

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

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

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

相关文章