使用 getClass().getResource() 加载资源
我正在尝试加载图像以用作应用程序中的图标。根据本教程,适当的方法是:
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 icon = new ImageIcon(path,"My Icon Image");
它工作得很好!因此,应用程序可以从显式定义的路径中获取图像,但不会使用 getResources() 拾取图像。在这两种情况下,路径变量的值是相同的。为什么它不起作用?类装入器如何找到资源?
谢谢。