我尝试使用 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
对象时,您是在告诉程序从文件系统中读取,这将使您的路径无效。不过,当从类路径读取时,您使用的路径是正确的,正如您应该做的那样。
请参阅 embedded resource 上的 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();
}
});
}
}
关于java - 将图像加载到 JLabel 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21856648/