我创建了一个扩展ImageIcon
的自定义类,以便传递文件url和给定颜色,它加载图像并重新绘制它。
该类打包在一个 .jar 文件中,我用它来开发不同的用户界面(我们称之为 UI.jar
)。
此类应该用于加载位于 UI.jar 内打包的文件夹中的图像、另一个 .jar 文件中打包的其他图像、具有其他 url 的其他图像(可能位于非文件夹中)包装在 .jar 中。所以我开发了这段代码:
BufferedImage bi = null;
try{
//CASE 1: the image related to this url is packed in a .jar file
bi = ImageIO.read(resourceClass.getResource(url));
}catch(Exception e){
try{
//CASE 2: the image related to this url is somewhere else
bi = ImageIO.read(new File(url));
}catch(Exception ee){
//CASE 3: none of the above
ee.printStackTrace();
}
}
这个方法有效,但问题是我总是将 resourceClass
作为扩展 ImageIcon 的自定义类的参数传递,这有点棘手和不舒服。
还有其他方法可以实现我的目标吗?
最佳答案
我在这里看到三种选择
- getClass().getResource(String)
- ImplementationClassName.class.getResource(String)
- Reflection.getCallerClass().getResource(String)
其中任何一个都可以完成这项工作。
如果你不喜欢前三个,你可以尝试这个,但这更难看。
StackTraceElement[] se = Thread.currentThread().getStackTrace();
//se[0] = Thread.getStackTrace()
//se[1] = your method
//se[2] = your callers method
Class x = Class.forName(se[2].getClassName());
x.getResource(url);
关于java - 从资源或不同文件夹加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36331408/