2013-07-13 34 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的默认值。

相关问题