How to add an ImageIcon to a JFrame?(如何将 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 ImageIcon 添加到 JFrame?
基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01