Java Image messes up when I run the .jnlp file
Question
I have a method that gets called at the start of my program, and it works fine when I run the jar, but when I run the jnlp file it crashes.
public void newImg(String i)
{
try
{
File file = new File(i);
img = ImageIO.read(file);
}
}
img is a bufferedImage, by the way.
Solution
Odds are the path you're giving to the file, or permissions, don't match. Put the File ctor into a try block, catch the exception, and find out what it is.
It should look something like this:
try {
File file = new File(i);
img = ImageIO.read(file);
} catch (Exception ex) {
// You probably want to open the java console, or use a logger
// as a JNLP may send stderr someplace weird.
Systemm.err.println("Exception was: ", ex.toString());
}
The code you have doesn't do anything with the exception.
You might want to look at the exceptions thread in the Java Tutorial.
update
See my comments. I just tried something and confirmed what I was thinking -- code with a try {}
and no catch
or finally
won't even compile. if this is really the code you think you're working with, you've probably been loading an old class file; this one hasn't compiled.
$ cat Foo.java
public class Foo {
public void tryit() {
try {
File f = new File(null);
}
}
}
$ javac Foo.java
Foo.java:3: 'try' without 'catch' or 'finally'
try {
^
1 error
$
OTHER TIPS
Maybe your not loading your image properly. Don't use the relative location of the file. This will be different for each OS. Your image in the JAR you should be loaded correctly like this:
URL url = this.getClass().getResource("image.jpg");
Image img = Toolkit.getDefaultToolkit().getImage(url);
This will load a file called image.jpg that is located in the same location as the class. You can also use things like File.pathSeparator if its in another location.
Use one of these two methods to load it as a resource:
http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String) http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
Make sure you have the correct file name/path.
Make sure you have file access to the file system.