sound will play in eclipse but not in exported jar file

前端 未结 2 383
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 05:14

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 05:54

    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.

提交回复
热议问题