我正在尝试加载图像以在我的应用程序中用作图标。根据此tutorial的适当方法是:
protected ImageIcon createImageIcon(String path, String description)
{
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
所以,我放置了文件的位置,并将其作为参数传递给该函数。这不起作用,即 imgURL 为空。当我尝试通过显式传递路径来创建 ImageIcon 时:
ImageIcon icon = new ImageIcon(path,"My Icon Image");
效果很好!因此应用程序可以从明确定义的路径中获取图像,但没有使用 getResources() 获取图像。在这两种情况下,路径变量的值是相同的。为什么它不起作用?类加载器如何找到资源?
谢谢。
最佳答案
getClass().getResource(path)
从类路径加载资源,而不是从文件系统路径加载。
关于java - 使用 getClass().getResource() 加载资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2343187/