2013-07-13 35 views

回答

1

我們可以利用其中包含擴展爲String類型HashtableImageIcon

Hashtable的是java.util

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

相關問題