如何在JFileChooser中显示文件的默认系统图标?

如何在JFileChooser显示文件的默认系统图标? 即JFileChooser中的文件图标应该与桌面和资源管理器上显示的图标相同?

例如,NetBeans图标在JFileChooser中的显示方式与桌面上显示的不同!

这个怎么做?

我们可以使用FileSystemView类并通过调用其中的getFileSystemView()静态方法来获取它的对象,然后使用getSystemIcon()方法获取File对象并返回它的图标。

FileSystemViewFileView类存在于javax.swing.filechooser包中。 File类位于java.io包中。

注意: FileSystemView不扩展FileView 。 因此你不能在jf.setFileView()使用FileSystemView对象

 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代表当前的框架。 假设编写此代码的类是JFrame子类

或者以简单的方式,

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

@JavaTechnical显示的方式是一种方式。 这是另一种(更容易)的方式。 将GUI(或至少文件选择器)设置为本机PLAF。 例如

文件选择器与原生PLAF

 import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.border.EmptyBorder; public class FileChooserIcons { public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); } // the GUI as seen by the user (without frame) JPanel gui = new JPanel(new BorderLayout()); gui.setBorder(new EmptyBorder(20, 30, 20, 30)); JButton browse = new JButton("Show File Chooser"); final JFrame f = new JFrame("File Chooser"); ActionListener showChooser = new ActionListener() { JFileChooser jfc = new JFileChooser(); @Override public void actionPerformed(ActionEvent e) { jfc.showOpenDialog(f); } }; browse.addActionListener(showChooser); gui.add(browse); f.add(gui); // Ensures JVM closes after frame(s) closed and // all non-daemon threads are finished f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // See http://stackoverflow.com/a/7143398/418556 for demo. f.setLocationByPlatform(true); // ensures the frame is the minimum size it needs to be // in order display the components within it f.pack(); // should be done last, to avoid flickering, moving, // resizing artifacts. f.setVisible(true); } }; // Swing GUIs should be created and updated on the EDT // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html SwingUtilities.invokeLater(r); } } 

当然,如果你感觉很勇敢,你可以创建一个自定义文件选择器,从文件浏览器GUI开始 。