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?
基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
