[英]How to display default system icon for files in JFileChooser?
如何在JFileChooser
显示文件的默认系统图标? 即JFileChooser
中的文件图标应该与桌面和资源管理器上显示的图标相同?
例如,NetBeans图标在JFileChooser
中的显示方式与桌面上显示的不同!
这个怎么做?
我们可以使用FileSystemView
类并通过调用其中的getFileSystemView()
静态方法获取它的对象,然后使用getSystemIcon()
方法获取File
对象并返回它的图标。
FileSystemView
和FileView
类存在于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。 例如
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开始 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.