1

如何在 中显示文件的自定义图标JFileChooser?好吧,我既不想要文件的默认系统图标,也不想要随附的默认图标JFileChooser。我想要我自己的图标。

我想通过扩展名设置文件的图标。我怎么能这样做?

4

1 回答 1

2

我们可以使用Hashtable包含扩展名作为String类型和ImageIcon

Hashtablejava.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 默认值。

于 2013-07-13T13:05:50.597 回答