sound will play in eclipse but not in exported jar file

拜拜、爱过 提交于 2019-12-01 09:38:47

The reason your sound is not playing because it is most likely not being compiled into your runnable jar and thus cannot be found. The best way to have it compile into a runnable jar is to create a source folder in eclipse, and then add your sound file in there. It will then be compiled into your jar

I struggled with this as well. You need to use

getClass().getSystemResource("pathToResourceFromClass")

For example, if your project structure is like the following:

-ProjectName

-----src

----------SomeClass.java

-----images

----------SomeImage.png

Then from SomeClass.java, you would use

getClass().getSystemResource("images/SomeImage.png")

to obtain the URL object which references that file. You could then pass that URL object to the constructor of ImageIcon if you want.

Note that getClass().getResource() does not work for images or sound files in a jar file!!! I've spent many hours on this, and getResource() does not work. You have to use getSystemResource(..) for resources within a jar file.

Let me know if you have any questions about this. I'd be glad to clarify any confusing points.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!