如何将 ImageIcon 添加到 JFrame? [英] How to add an ImageIcon to a JFrame?

查看:41
本文介绍了如何将 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"));

这篇关于如何将 ImageIcon 添加到 JFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆