Sound does not play when I run the JAR, but it does when I run it in eclipse.
Here is where I load the clips: (the files are loaded from the directory of the jar, No
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.
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