有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在JFileChooser中显示文件的自定义图标?

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

我想按文件的扩展名设置文件的图标。我怎么能这么做


共 (1) 个答案

  1. # 1 楼答案

    我们可以使用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默认值