How to make a jar runnable in order to save images - java

I have a problem:
I put my images in my project folder, for example, E:\All Work IT\Java All\JavaWork\TestingDB and when I use this line of code to use the images
ImageIcon icon = new ImageIcon("start.png");
It works perfectly!
But when I want to make a Runnable jar file (Export -> select Runnabable jar file) and open the specific jar, the images don't appear on the buttons, menu, and so on.
Where do I need to put my images to solve this problem, and with what code?
Thanks.

new ImageIcon(file) specifies a local file which won't work inside a JAR.. Try changing the line to use a the class loader.
new ImageIcon(getClass().getResource("/start.png"));
If you're in a static context
new ImageIcon(Foo.class.getResource("/start.png"));
I'm unsure of your project structure or IDE, if any, so I'm unable to make any recommendations on where images should go. Just make sure the images are included in the JAR export and end up at the top level, or structure matching your getResource() call

One if the simplest ways would be to include the images within the jar file itself, this reduces the number of resources you'll need to deploy; much easier to deploy a single jar then a jar file and a bunch if images
It also reduces the possible issues with execution context and having to calculate the relative paths
Who you achieve this will depend on how you are building the jar, for instance in Netbeans and Eclipse, you can copy the images into the src directory. In maven, you'd need to include the images in the resources directory
This will change the way you need to use to load the images or resources
You will need to use Class#getResource or Class#getResourceAsStream depending in your needs, for example
ImageIcon img = getClass().getResource("/start.png");
Remember, you will need to use the full path to the image from the context of the src directory
This means if you place the resources within the images directory under the src directory, then you will need to use /images/start.png for example

Related

Packaging an Eclipse Program With External Files

I'm not sure if this was answered previously, I tried searching for the kind of question I am asking, but I couldn't find something satisfactory. If someone could point me to a similar question, that would help.
What I am trying to do is to package an eclipse program that has external files, such as images, into a single file, rather than a jar file and the supporting files placed in the same directory.
I am not sure if that is even possible, but is there some way in eclipse that would allow you to somehow package the external files along with the jar file in a single, neat file that can be executed easily?
EDIT:
Thanks to ortis and Thorbjørn Ravn Andersen, I figured out how to do it. Here are the steps for working it out:
Firstly, ensure that all of your external files are in your src folder, not in your bin or workspace or whatever else. If you have packages in your project, they will appear as folders and the external files must be placed into those folders for use within that package.
As for calls to the external files, don't do something like this:
Image img = new Image("fileName");
Rather do this:
Image img = new Image(getClass().getResourceAsStream("fileName"));
while ensuring that "fileName" is in the src folder or package folder, if you have packages.
Some points:
-If you are initializing a global variable using a file name that is outside of your main constructor or function call, getClass(), won't work. Use:
yourClassName.class.getResourceAsStream("fileName");
-if your using JavaFX Scenebuilder and you need to package your external CSS file, here is a solution that will help you load the style sheet in your program instead of using the .fxml file to do it.
-An InputStream variable can be assigned the result of
getClass().getResourceAsStream("fileName"));
and be used instead of the whole mess.
Yes. You must reference all external files as inputstreams instead (because you want the classloader to get them from inside a jar file), and then wrap the resulting single jar file as an EXE file using http://launch4j.sourceforge.net/

Location of image in exported project folder

In my current code I write the specific location of the images I want to use in my project, now, these locations are only correct until I move the image to a different directory or open the application in a different computer.
Where do I place the images (where to place them in the exported folder) I want to use in my project?
The exported project is a zip file, once extracted, I have 2 folders within the extracted folder, one named nbproject other is src, one text file named build another .mf file called manifest inside nbproject I have two text files and two .properties files inside src I have my four classes.
Where do I put the images I want to use in the project? And once I place them, what directory do I write in my project?
Here's an example of how I use an image:
// Main menu background image
bgg[0] = new ImageIcon("D:/NetBeans/NetBeans projects/Java/Project Images/bg option for Vanguard.jpg").getImage();
And then I draw the image all over the screen
My exported folder contents:
http://i.imgur.com/qd4PeJo.png
http://i.imgur.com/W5YQ7OC.png
EDIT: Thought it worked but it keeps giving an exception on other people's computers, perhaps this isn't the reason beause I moved the images around in my PC and it worked but still.
Since you are writing the directory in your code.
bgg[0] = new ImageIcon("D:/NetBeans/NetBeans projects/Java/Project Images/bg option for Vanguard.jpg").getImage();
When you run the project in another computer or move the image to another location, the program can't find the path to the picture, so there is an error. Instead of using the full path. Copy the images to your project folder and use relative paths.For instance : "images/Vanguard.jpg".
The path where your program looks for resources can depend on how you run the program. If you ran it via console/terminal the initial path starts at the path of the *.class file you ran. If you run it from an IDE this path may change, in Eclipse the path starts at the Project dir and not the src folder. You can find out the exact path by calling System.getProperty("user.dir") that will return the current working path as a String.
Don't use a strict path, use a relative path like so:
Main.java
String path = "Project Images/bg option for Vanguard.jpg";
bgg[0] = new ImageIcon(getClass().getResource(path)).getImage();
In order for this to be loaded, you must place a folder called Project Images in the directory in which your Java files are. Then place the image bg option for Vanguard.jpg in this folder. Be sure to compile the program in you IDE so it can make a copy for the compiled version.

Exported jar finds some files (not all) even though the paths are the same [duplicate]

This question already has answers here:
I'm trying to export a runnable jar in Eclipse, but I need it to include some other files necessary for running my program
(3 answers)
Closed 8 years ago.
When I run my program from eclipse, it shows up fine, the images from Resources\ show up, as do the sounds from the same place, and the text files are found properly. However, when I export my jar, and copy the resources into it with 7Zip, the images will work, but the sounds and the text files can't be found, even though they're in the same folder, with the same path used to find them in my code. I can fix this by putting a folder next to the jar file named Resources, and put everything in there, but I'd like to know why just putting it in the jar file only worked for the images, and how I can get it to work with the text and audio files as well.
An example to show you what I mean:
File inventory = new File("Resources/inv.txt");
threadpath = "Resources/threads.wav";
enemy1 = new Sprite(new Texture("Resources/miniForestGolem.png"));
When I run it in eclipse, all three work fine, but when I export it, and put the resources folder in the jar file, only the image works.
Edit:
I know how to include my resources, and have done so, I'm asking about how/why some of the resources aren't able to be accessed, even after adding them in.
Ok, from your comments we can infer the difference between executing it from eclipse and executing it from a .jar.
From eclipse: it works, because all that new File(...) find an actual file in Resources/
From the .jar: it won't work, since there is no file in a relative ./Resources/ path from the execution path of the application.
The way to make it work is the next:
Make sure Eclipse recognizes Resources/ as a source folder (right-click on project properties, Java Build Path, and add it as a source path)
Look for a replacement for your API methods that, instead of File objects, use InputStreams. Once you have it, retrieve all your resources as InputStreams taken from the classpath. If you are inside MyClass.java, do this: MyClass.class.getClassLoader().getResourceAsStream("Resources/inv.txt"), etc.
What you have achieved by doing this: instead of File objects built on actual operating system files, you will be retrieving InputStreams read straight from your java application classpath. This way, you can package them into a jar, or into a WEB-INF/classes directory inside a web application, or a library folder in some application servers... wherever you like as long as it is into the application classpath. I would do this if I had to package your application in a portable and usable way.

Exporting Images with JAR in Eclipse (Java)

I've been working on a little project that requires external images for display. I'm not all that familiar with how to use Eclipse and this is my first time attempting to export a completed project so I can share it with others. Right now, it seems the only way I can get my images to show up is if I assign a specific folder on my hard drive and have the image paths in the code go to that.
I'm looking for a way to export the images as part of my JAR or as part of the same package so when I go to send this program to other people, I don't have to send them a separate archived folder of images. I'd also be interested in learning what I need to do to have my code reference the images within that package so they'll work without an external folder.
I have read about some kind of package system within Eclipse, but have thus far had no luck in figuring out how to use it. Could use some explicating!
Thanks in advance to anyone willing to give me their two cents.
Something I would have found useful with this answer is the following: make sure you put your images/files in the same eclipse folder (or sub-folder below) as your source code. I created a folder "images_ignored" using eclipse, added it to the build path but still it refused to be included in my JAR file (when creating an executable JAR).
Just drag the images folder into your Eclipse project, then choose to "Copy New Folder" or "Copy File and Folder" depending on Eclipse version, and then right click on the image folder (in Eclipse) and --> build path "use as source folder".
you might need to load them as class path resources if they are within a jar. see: getClass().getClassLoader().getResourceAsStream(...)
Use getResource() to load the images:
ImageIcon qmarkIcon = new ImageIcon(getClass().getResource("images/mark.gif"));
If you're using JDK 1.7 or JDK 1.8, you might want to use the NIO.2 API.
for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
if ("jar".equals(provider.getScheme()))
return provider.newFileSystem((new File(Start.class
.getProtectionDomain().getCodeSource().getLocation().toURI()))
.toPath(), new HashMap<String, Object>());
}
If you enter this code into a method that returns a java.nio.file.FileSystem, you can call the method to get the FileSystem for the JAR file.
To get the path to access the files inside your JAR file, you can use the following method, which then allows you to read the files however you may want.
fileSystem.getPath("/images/image.gif")
If you would like to be able to run this in Eclipse, make sure you surround the call to the method with a try/catch IOException and assign to your FileSystem object the following.
new File(Start.class.getProtectionDomain().getCodeSource().getLocation().toURI())
.toPath().toString();
This will allow you to run your program whether it's compressed into a JAR file or not.
I recommend you get used to using NIO.2, since it is a very powerful API.
If you add a folder to build path you can retrieve the images either in eclipse and when you exported it in jar file, just remember to don't reference the image with the path like img/myImage.gif but only myImage.gif !

Java in Eclipse: Where do I put files on the filesystem that I want to load using getResource? (e.g. images for an ImageIcon)

I know the file needs to be where the getClass().getResource(filename) can find it, but I don't know where that is.
I'm interested both in where to put the files on the filesystem itself, and how to go about using Eclipse's functionality to set up the resources.
For Eclipse, typically all you need to do is set up a folder somewhere within your source code directory. For instance, if the directory containing your source is /src then you can create a /src/resources folder to place your images/files in. Then, within your class you do a getResource("/resources/image.png") to retrieve it.
You can also place the image/file within the same folder/package as the class trying to access it if you wish (example: place the image.png in the com.mycompany package with the com.mycompany.Foo class that needs to access it and call getResource("image.png")), but I've found it's easier to keep resources like images and other files in their own special directory outside of the class folders -- they're just easier to manage that way.
In Eclipse, whenever you do a build, the files within this resource directory will be copied over into your build directory along with your compiled classes.
It's important to note that if you have "Build Automatically" turned on in Eclipse (as most people do) any resources in this directory that get changed outside of Eclipse (i.e. you edit an image using an image editing tool) that the IDE may not always detect this change. Usually doing a refresh on the project folder will ensure that the file gets updated in the build in these situations.
You can either put them in the src folder alongside your classes, or you can create a new source folder for the purpose (usually called resources), although you'll locate them identically from code.
Then you get at them using getResource("/com/x/y/foo.png").

Categories

Resources