[英]How to load icon from resource in Java?
Possible duplication (solved): https://stackoverflow.com/a/1133132/783469 可能重复(已解决): https : //stackoverflow.com/a/1133132/783469
I have icons (jpg, png) for my application, which is stored in my directory /var/tmp/gameXbox/src/image/<here>
. 我的应用程序有图标(jpg,png),它存储在我的目录/var/tmp/gameXbox/src/image/<here>
。 Now, How can i use them in application, without using hard link but as resource? 现在,我如何在应用程序中使用它们,而不使用硬链接作为资源?
Example: not working 示例:不工作
IconForMyButton = ImageIO.read(new File(
ClassLoader.getSystemResourceAsStream("image/button1.png")
));
Works when i do with hard link: 当我使用硬链接时工作:
IconForMyButton = ImageIO.read(new File(
"/var/tmp/gameXbox/src/image/button1.png"
));
Resource loading takes place in the classpath, relative to the current package. 资源加载发生在类路径中,相对于当前包。 If /var/tmp/gameXbox/src/
is in your classpath, then: 如果/var/tmp/gameXbox/src/
在你的类路径中,那么:
ImageIO.read( ClassLoader.getSystemResource( "image/button1.png" ) );
However, usually the src
folder is not included in the classpath by IDEs. 但是,通常IDE的类路径中不包含src
文件夹。 Try adding the image to the bin
folder. 尝试将图像添加到bin
文件夹。
I usually use class.getResource for this kind of operation : 我通常使用class.getResource进行这种操作:
YourClass.class.getResource("image/button1.png")
i use it to retrieve the file from a jar archive but should work also to retrieve from filesystem resources. 我用它从jar存档中检索文件,但也应该从文件系统资源中检索。
Images do not go into a source folder but into a resource folder. 图像不会进入源文件夹,而是进入资源文件夹。 Fix your IDE and use Maven and it will work with getResourceAsStream
with the current context classloader. 修复您的IDE并使用Maven,它将与当前上下文类加载器的getResourceAsStream
一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.