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的默認值。