I've written a Snake clone in the process of learning how to program in Java. It is an applet that uses images (loaded in the init() method using getImage(getDocumentBase(), "gfx/image.png");
When I run the applet in my IDE (Eclipse) it runs fine and all the images are shown.
My goal however is to create an executable jar file that I can pass around easier than an applet. So I created a new class and used a JPanel to host my applet. Now the problem is that getDocumentBase() always returns null, resulting in the images not being found on the filesystem, resulting in an empty screen.
I know the game runs cause I can navigate all the menus and see all the text that is printed. It's just the images that aren't loaded.
Is there any way around this? Should I load my images another way?
Thanks
You can load resources from within you jar-file by using the getResource() method from Class. On DevX there's a nice tutorial showing you how to do that for applets and applications:
http://www.devx.com/tips/Tip/5697
There is also an article from Oracle describing how to access resources in a location-independent manner:
http://download.oracle.com/javase/1.4.2/docs/guide/resources/resources.html
Basically you're accessing an image like this:
URL myurl = this.getClass().getResource("/myimage.gif");
Toolkit tk = this.getToolkit();
img = tk.getImage(myurl);
Load your image like this instead:
public void init() {
URL url = getClass().getResource("/gfx/image.png");
Image image = getImage(url);
}
Then add your gfx/image.png file to your jar and keep the path. Note that jar files are just zip files.
Related
This question already has answers here:
Java Swing: Displaying images from within a Jar
(5 answers)
Closed 9 years ago.
Heres how i call the image
Icon logoOne = new ImageIcon("logo.png");
// LOGO
JLabel imageLogo = new JLabel(logoOne);
imageLogo.setPreferredSize(new Dimension(200, 50));
Its just added to a panel in a JFrame and works fine when running in eclipse but doesnt show up when exported to JAR.
can anyone help ?
When exporting your JAR file, you've to make sure you're also including the image files in your JAR file. For example: If you have a folder called 'res' containing the images, you have to check the checkbox before this folder in order to make sure this folder, and the images are being included.
You might want to add some trouble shooting code. For example: Add some code that prints in the console if this image file exists. Export your JAR file, run your JAR via the console/terminal and check the result. If this shows you the image doesn't exists, you know it's a problem with your exported JAR file.
You might want to try reaching the image as a resource steam, give the following code sample a try:
java.net.URL logoOneUrl = getClass().getResource("logo.png");
Icon logoOne = new ImageIcon(logoOneUrl );
When you call
Icon logoOne = new ImageIcon("logo.png");
You are reading the image from a file (see javadoc). When you export to the jar, this file is no longer available, so you need to use ClassLoader#getResourceFromClasspath() or use one of the other constructors.
That depends on how you added the Image to the jar file.
In the normal case, the image lies in one of your source folders, and eclipse takes care of exporting it into the Jar file. If that is the case, you can load the via the ClassLoader. there are several methods for that. I mostly use this.getClass().getResourceAsStream("logo.png"). If you only use the standard Classloader (which would be the normal case) this will work.
Don't get your image as a file as you're currently doing so. Instead get it as a resource. If you search this site, you'll find similar questions about occurring 2-4 times per week.
i.e.,
String imageResource = //.... string to image resource path
Image myImage = ImageIO.read(getClass().getResourceAsStream(imageResource));
Icon logo = new ImageIcon(myImage);
Note that the imageResource String is the String that represents the resource path to your image. This will depend on where your image is held in the jar file and where it is relative to the class files, information that we don't know at the moment.
I am trying to fix this problem. Trying different solutions but nothing works. I am using NetBeans IDE. I created a project with this structure and files:
E:\java\project\ecadpb\src\ecadpb
The image files are in
E:\java\project\ecadpb\src\
I have specified working folder for my project in Netbeans as E:\java\project\ecadpb
I have created my image icons like this
new ImageIcon("device21.png");
In my source file, it works perfectly while running the project in Netbeans but images are not showing up when I build and run my JAR file separately. But the image files are inside the JAR.
I have also tried the answers for the same question asked previously.
URL imageUrl=getClass().getResource("device21.png");
new ImageIcon(imageUrl);
But it doesn't work in my case. I am building a JAR file for the first time. Can anyone help me with this!!
A simple way of doing this will be to add the image in your classpath or a directory in your classpath say img as shown below:
E:\java\project\ecadpb\src\main\java\img\device21.png
And then load your image from this location like this:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("img/device21.png");
ImageIcon icon = new ImageIcon(resource);
Create a source folder called Images (ie if you're using eclipse, right-click your project -> new ->sourceFolder). Call it whatever you want, i called my Images. Put some images in it.
Now i had JLabels where i gave them ImageIcons. Look at the following code.
ImageIcon BPawn;
ImageIcon WPawn;
JLabel Label = new JLabel[8][8] //2D array of labels that gives each spot a position.
public void setPieces(){
//set up pawns in their respective positions.
BPawn = new ImageIcon("Images/BPawn.png", "BPawn");
WPawn = new ImageIcon("Images/WPawn.png", "WPawn");
for(int i=0;i<Label[0].length;i++){
Label[1][i].setIcon(BPawn);
Label[6][i].setIcon(WPawn);
}//end for
}//end setPieces.
There is a lot more in setPieces() method, but this glimpse is how you would reference the images in your source folder when you create an executable jar and want the images to show up.
I think answer could be one these suggestions here
I have used a similar approach,
a) Specify the package path to the image file name.
b) Make sure that the image file is not ommited by your build scripts and that it is present in your jar file.
I am developing JNLP Application and using maven-webstart plugin to create JNLP. When running the application in my local, it works correctly but when I run in Tomcat Server using jnlp, it does not load images and also does not give any exception.
I am loading images as below
new ImageIcon(getClass().getResource("/icons/save.png"))
What is wrong with my code?
Where are your icons located? How do you run a jnlp application inside tomcat? Assuming you don't have a lot of images, you can package them inside one of your packages. Just create a package called com.yourproject.resources and dump some images there. Then the way to access them would be:
//define it in some class
public URL obtainImageResource ( String nameOfResource )
{
return getClass().getResource( "/com/yourproject/resources/" + nameOfResource );
}
Do get them with a URL.
Then to create the stuff you need:
BufferedImage yourImage = ImageIO.read( yourclaass.obtainImageResource( "yourimagepng.png" ).openStream() );
Note some things: In my setup you need to package your images into your jar.
It's hard to say without more information. You might use jar -tf to see if the images are in the JAR file. In the meantime, here's a working JWS application that loads images, for reference.
I have pretty much tried everything but still have this same problem. I have the following setup: I have a images.jar containing a folder called 'images' in which there are multiple image files. I add images.jar to the java build path of the project in eclipse, and i've been trying to use the following code to access the individual images in the jar:
URL url = this.getClass().getResource("images/a.png");
ImageIcon icon = new ImageIcon (url);
Unfortunately, the URL object is always NULL. I don't think this has anything to do with where I put images.jar file as it is added to the classpath in eclipse. I have also tried using the path '/images/a.png', but still the same problem. Any suggestion would be extremely welcome! Thanks.
Try this:
URL url = this.getClass().getClassLoader().getResource("images/a.png");
ImageIcon icon = new ImageIcon(url);
Without getClassLoader() invocation you are only able to access resources in JAR file where the code is stored.
I couldn't reproduce your problem, but my theory is that you are running the class from a different place than you think you are -- that the image and the class are in different jars, or the class is read directly from the class file.
I am working on a small basic GUI program that gets the files from my resources and gets the names of the files and places them in a combo box. for example i just have a file inside the same package called images and trying to get the files names. the way I get the file is by using the getResoure() like so
java.net.URL url = FileDemo.class.getResource("images");
but when I try to get the files inside the directory
File urlfile = new File(url.toString());
String[] files = urlfile.list();
the first line will convert the url to string and create a file object but when I try to get the list of files inside the directory it returns a null to the array of strings.
I broke down the code and used the debugger in netbeans found out, when it did the SecurityManager check it wouldn't pass.
My question is are the files inside the project protected or there is no way to access them using the list() and listFiles() or am i doing something wrong? Also I ran the same script on my schools computer which they have windows 7 the code above worked. But when i ran it on my mac and even 2 win xp machines it just didn't work? why is that ?
I hope this makes sense i am just stuck here still a new to java
Thanks in Advance.
The class to getResource(String) is returning a URL to images but there's no guarantee that this is a file URL (beginning "file:"). If your class is embedded within a jar file this certainly won't be the case, hence why it fails in some situations and not others.
If your intention here is to actually make a portion of a file system visible to the user then I'd recommend avoiding getResource altogether, which is typically more useful when your application wishes to locate and load resources such as icons or config files.
Instead, you could use JFileChooser, which is a rich Swing component for navigating the file system and selecting files.