Need alternative ways to load icons
Brought to you by:
daveselinger,
ribizli
For certain deployments, such as Java Web Start, it
would be better to have the icon in the jar and loaded by
the classloader. I realize there is probably some current
need for having the icon as a file so Win32/KDE can
locate it, but if there is a way around this, it would be
well worth it.
Logged In: YES
user_id=11633
Note, I've come up with the following work-around:
/**
* Extracts an icon resource from the ClassLoader
to a auto-deleting temporary file.
*/
protected static File extractIconToFile(String name)
throws IOException
{
// Find the icon resource
URL iconURL =
TrayIcon.class.getResource(name);
if(iconURL == null) throw new
IOException("Resource not found in classpath: " + name);
// Prep the temp file
File iconFile;
int dotIndex = name.lastIndexOf('.');
if(dotIndex > 0) {
String prefix =
name.substring(0, dotIndex);
String suffix =
name.substring(dotIndex);
iconFile =
File.createTempFile(prefix, suffix);
}
else {
iconFile =
File.createTempFile(name, "");
}
iconFile.deleteOnExit();
// Extract the icon
BufferedInputStream in = null;
BufferedOutputStream out= null;
try {
in = new
BufferedInputStream(iconURL.openStream());
out = new
BufferedOutputStream(new FileOutputStream(iconFile));
byte[] buffer = new byte
[1024];
int read = 0;
while((read = in.read(buffer))
>= 0) {
out.write(buffer,
0, read);
}
}
finally {
if(in != null) try { in.close(); }
catch(IOException e) {}
if(in != null) try { out.close
(); } catch(IOException e) {}
}
return iconFile;
}
Logged In: YES
user_id=607101
Your work-around is great. I'll include it to the
SysTrayMenuIcon class.