简体   繁体   English

如何将ImageIcon添加到JFrame?

[英]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. ImageIcon从指定文件创建的图像。 The image file is in the seam directory the java file exist. 图像文件位于java文件存在的seam目录中。

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


    }

If your icon is beside the TimeFrame java file, you should use 如果您的图标位于TimeFrame java文件旁边,则应使用

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

Will u try this one? 你会试试这个吗?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM