Reputation: 734
To give path to a resource eg:- image, in javafx, we can do as :-
ImageView imgView_btnEndCall = new ImageView(new Image("/clientgui/image/callend.png"));
But to give path to a resource in swing, the following code works
FileInputStream fis = new FileInputStream("src/soundtest/sound/sound.wav");
The difference I found is necessity to put 'src' in swing. And when I run the jar file from dist folder, swing program doesnt work but javafx program works. Problem is because the jarfile compress the project including all the packages and files. When javafx program tries to access some resource, it is able to access, callend.png file inside image folder inside clientgui folder. But swing application cant access as we have given 'src' folder in the code. How to solve the problem. How to include the resource directory in swing so that the jar file can access the resource.
Upvotes: 1
Views: 1651
Reputation: 734
Well thanks to durron597, my code worked. As I mentioned in my question, the problem was jar file doesnt have src folder and can't access the resource as I mentioned in my question. Taking the resource using ClassLoader solved the problem. Here is my final code
AudioStream audio = new AudioStream(getClass().getResourceAsStream("sound/sound.wav"));
AudioPlayer.player.start(audio);
Here, package name is soundtest and inside that package, there is another folder called sound which has a wav file sound.wav
soundtest
|-sound
|-sound.wav
Upvotes: 1
Reputation: 32343
Don't use FileInputStream
, use the ClassLoader
, e.g.
getClass().getResourceAsStream("sound/sound.wav");
This will load the file from the directory structure contained in your jar. The src
folders won't exist anymore when the jar
is created, they will be an embedded resource (thanks @AndrewThompson for the buzzword).
Read more in this question: Embedding resources (images, sound bits, etc) into a Java project then use those resources
Upvotes: 2