0
如何在JFileChooser
中显示文件的自定义图标?那么我既不需要该文件的默认系统图标,也不需要JFileChooser
附带的默认图标。我想要我自己的图标。如何在JFileChooser中显示文件的自定义图标?
我想通过扩展名为文件设置图标。我怎么能这样做?
如何在JFileChooser
中显示文件的自定义图标?那么我既不需要该文件的默认系统图标,也不需要JFileChooser
附带的默认图标。我想要我自己的图标。如何在JFileChooser中显示文件的自定义图标?
我想通过扩展名为文件设置图标。我怎么能这样做?
我们可以利用其中包含扩展为String
类型Hashtable
和ImageIcon
Hashtable
的是java.util
包
FileView
是javax.swing.filechooser
包
// 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"));
在类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");
}
}
,并使用此代码,
MyFileView m=new MyFileView(table,new ImageIcon("diricon.png"));
JFileChooser jf=new JFileChooser();
jf.setFileView(m);
jf.showOpenDialog(this);
如果我们不通过扩展,或者如果我们要为硬盘驱动器自定义图标想,我的电脑,然后我们可以使用UI的默认值。