How to get a platform-dependent Image from JNLP?
Hi,
I've read (not yet tried) that to load an image from a JNLP file it is necessary to pass from a classloader: in the case of an JInternalFrame, instead of
setFrameIcon(new ImageIcon("src\\icons\\image.png"));
is necessary to use
setFrameIcon(new ImageIcon(getClass().getResource("src\\icons\\image.png")));
However, to set a icon in a JFrame, the standard way is
setIconImage(Toolkit.getDefaultToolkit().getImage("src\\icons\\image.png"));
which is a platform-dependent manner to retrieve an Image, because the JFrame is a root component depending directly on the OS, I think. But how to do that if we're loading images from a JNLP?
Thanks in advance
# 1
Your question indicates some confusion, especially
between URL's and Files (or Strings that represent a
path to a File).
For example, the String ..
"the\\path"
..might indicate a path to a File on *windows*.
To be X-plat, it would need to be ..
"the" + System.getProperty("file.separator") + "path"
..which would put a separator appropriate for any
platform. On *nix and Mac, that would produce..
"the/path"
When it comes to URL's the slash is *always*
a forward slash.
Your two methods mix up both arguments that
accept URL's, and arguments that accept Strings
meant to represent Files, so some of them are
Windows specific, and others are just plain wrong.
Here is a runnable example..
import java.net.URL;
import java.io.File;
class TheSeparator {
public static void main(String[] args) throws Exception {
// get a File handle to the source file
File file = new File( "TheSeparator.java" );
// get an URL for that file
URL url = file.toURL();
System.out.println("URL: \t" + url +
"\nFile: \t" + file.getCanonicalPath());
}
}
The output here is..
URL:file:/D:/projects/TheSeparator.java
File:D:\projects\TheSeparator.java
Press any key to continue . . .
Check the contructors and methods in the JavaDocs
and you will see what I mean about mixing File
and URL references.
In any case, to focus on the URL way, I
suggest breaking it down and proceeding
something like this....
// forward slash for URL's!
URL url = this.getClass().getResource("src/icons/image.png");
// check it!
System.out.println( url );
// construct the ImageIcon
ImageIcon icon = new ImageIcon( url );
// check it!
System.out.println( icon );
setFrameIcon( icon );
...
Obviously they can all be compacted into
a single line once working (though I consider
that to be bad programming practise), but for the
moment, it would definitely be best to do each
as a separate statement, then check the result.