Getting the Small Icon
For all platforms, the FileSystemView class provides a method for getting the small icon (16x16). To get the icon, you must specify a file on the file system for which you want to get an icon. The following code example shows how to use this class to get the icon:
//Create a temporary file with the specified extension
File file = File.createTempFile("icon", ".doc");
FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(file);
//Delete the temporary file
file.delete();
In the example above, a temporary file is created with the extension for the specified document type. This file is passed to the instance of the FileSystemView class to get the icon. This will return the default icon size which is 16x16 pixels on most platforms. Once you have the Icon, you can display it in most Swing controls such as a JLabel, JButton, JMenuItem, etc.
Getting the Large Icon
Unfortunately, there isn't a standard API call to get the larger icons (32x32) for document types. For platforms using the Sun JVM, there is an undocumented class called sun.awt.shell.ShellFolder that does provide this functionality. The following code is a modified version of our previous example with changes to show how to use the sun.awt.shell.ShellFolder class.
import sun.awt.shell.ShellFolder;
...
//Create a temporary file with the specified extension
File file = File.createTempFile("icon", ".doc");
ShellFolder shellFolder = ShellFolder.getShellFolder(file);
Icon icon = new ImageIcon(shellFolder.getIcon(true));
//Delete the temporary file
file.delete();

7 comments:
Thanks, this is exactly what I was looking for.
This comment saved my life today. Thanks
Very useful, thanks!
cool, thanks!
Excellent i was looking for it
THANKSSSSS!!!!!!!!!! JUST WHAT IVE BEEN LOOKING FOR !!!!!!!!
Using this code gives the same icon for all file types. Its a plain white icon. What do i need to do get the correct file icon for each different file type?
thanks
Post a Comment