How to display default system icon for files in JFileChooser?

前端 未结 2 677
余生分开走
余生分开走 2021-01-05 13:17

How to display default system icon for files in JFileChooser? i.e. the icons of the files in JFileChooser should be the same as the icons that app

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 13:29

    We can use the FileSystemView class and get it's object by calling getFileSystemView() static method in it and then use the getSystemIcon() method which takes a File object and returns it's icon.

    FileSystemView and FileView classes are present in javax.swing.filechooser package. File class is in the java.io package.

    Note: FileSystemView does not extend FileView. Hence you cannot use FileSystemView object in jf.setFileView()

    JFileChooser jf=new JFileChooser();
    jf.setFileView(new MyFileView());
    jf.showOpenDialog(this);
    
    class MyFileView extends FileView
    {
          public Icon getIcon(File f)
          {
          FileSystemView view=FileSystemView.getFileSystemView();
                return view.getSystemIcon(f);
          }
    }
    

    this represents the current frame. Assume that the class in which this code is written is sub class of JFrame

    Or in a simple way,

    jf.setFileView(new FileView(){
                public Icon getIcon(File f)
                {
                    return FileSystemView.getFileSystemView().getSystemIcon(f);
                }
            });
    

提交回复
热议问题