Reputation: 9357
How to display custom icons for files in JFileChooser
? Well i neither want the default system icon for the files nor the default icon that comes with JFileChooser
. I want my own icon.
I want to set the icon for a file by it's extension. How could i do that?
Upvotes: 1
Views: 810
Reputation: 9357
We can make use of the Hashtable
which contains the extension as String
type and an ImageIcon
Hashtable
is in java.util
package
FileView
is in javax.swing.filechooser
package
// Create a hashtable for String,ImageIcon
Hashtable<String,ImageIcon> table=new Hashtable<>();
// Add extensions and icons
table.put(".txt",new ImageIcon("txtfile.png"));
table.put(".doc",new ImageIcon("docfile.png"));
table.put(".ppt",new ImageIcon("pptfile.png"));
table.put(".lnk",new ImageIcon("link.png"));
table.put(".png",new ImageIcon("image.png"));
table.put(".gif",new ImageIcon("image.png"));
table.put(".jpeg",new ImageIcon("image.png"));
table.put(".jpg",new ImageIcon("image.png"));
In the class MyFileView
class MyFileView extends FileView
{
Hashtable<String,ImageIcon> table;
ImageIcon dirIcon;
public MyFileView(Hashtable<String,ImageIcon> table,ImageIcon dirIcon)
{
this.table=table;
this.dirIcon=dirIcon;
}
public Icon getIcon(File f)
{
// Do display custom icons
// If dir
if(f.isDirectory())
{
if(dirIcon!=null) return dirIcon;
return new ImageIcon("myfoldericon.png");
}
// Get the name
String name=f.getName();
int idx=name.lastIndexOf(".");
if(idx>-1)
{
String ext=name.substring(idx);
if(table.containsKey(ext))
return table.get(ext);
}
// For other files
return new ImageIcon("myownfileicon.png");
}
}
And the code to use this,
MyFileView m=new MyFileView(table,new ImageIcon("diricon.png"));
JFileChooser jf=new JFileChooser();
jf.setFileView(m);
jf.showOpenDialog(this);
If we don't want by extension or if we want to set a custom icon for hard drive, my computer then we can make use of the UI defaults.
Upvotes: 2