[英]Load Image into JLabel not working
我尝试使用JLabel
显示图像。 这是我的项目导航器:
我想从SettingsDialog.java
使用以下代码显示图像:
String path = "/images/sidebar-icon-48.png";
File file = new File(path);
Image image;
try {
image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
header.add(label); // header is a JPanel
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
该代码引发异常: 无法读取输入文件!
图像的路径是否错误?
不要从文件中读取,而是从类路径中读取
image = ImageIO.read(getClass().getResource(path));
-or-
image = ImageIO.read(MyClass.class.getResource(path));
当使用File
对象时,您要告诉程序从文件系统读取,这将使您的路径无效。 从类路径读取时,您正在使用的路径是正确的,但是应该这样做。
请参阅有关嵌入式资源的Wiki。 另请参见getResource()
更新测试运行
package org.apache.openoffice.sidebar;
import javax.swing.*;
public class SomeClass {
public SomeClass() {
ImageIcon icon = new ImageIcon(
SomeClass.class.getResource("/images/sidebar-icon-48.png"));
JLabel label = new JLabel(icon);
JFrame frame = new JFrame("Test");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SomeClass();
}
});
}
}
“ /images/sidebar-icon-48.png”是根路径。 在Windows上,取决于当前驱动器,驱动器为c:\\ images \\ sidebar-icon-48.png或d:\\ images \\ sidebar-icon-48.png(java将/转换为\\-不是问题)。 Linux映像是根目录/images/sidebar-icon-48.png的子级。需要相对于类或相对于具有该类的jar进行加载(如果您不希望将图像存储在jar中。
在大型项目中,最好将图像和其他资源保存在jar之外,因此jar较小,更重要的是,它易于更改资源,而无需摆弄jar / wars。
由于您似乎要为开放式办公室增加附加功能,因此您必须将所有内容保存在罐子中,因此peeskillet答案是正确的。 但是请确保将图像文件夹包装在罐子中。 使用jar命令解压缩jar或将文件重命名为zip并解压缩。
尝试直接使用此:
JLabel label = new JLabel(new ImageIcon(path));
并删除这些行:
File file = new File(path);
image = ImageIO.read(file);
如果错误仍然存在,请粘贴以下错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.