如何将ImageIcon添加到JFrame?

Ber*_*ard 5 java swing jlabel jframe imageicon

我正在尝试将图像添加到一个帧但看起来它不起作用.ImageIcon从指定文件创建的图像.图像文件位于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);
        }


    }
Run Code Online (Sandbox Code Playgroud)

pre*_*edi 5

如果您的图标位于TimeFramejava文件旁边,则应使用

java.net.URL imgUrl = getClass().getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
Run Code Online (Sandbox Code Playgroud)

要么

java.net.URL imgUrl = TimeFrame.class.getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
Run Code Online (Sandbox Code Playgroud)

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

System.out.println(System.getProperty("user.dir"));
Run Code Online (Sandbox Code Playgroud)


DRa*_*lav 5

你会尝试这个吗?

 ImageIcon ImageIcon = new ImageIcon("me.jpg");
    Image Image = ImageIcon.getImage();
    this.setIconImage(Image);
Run Code Online (Sandbox Code Playgroud)