JFileChooser 的默认界面比较丑,一般的使用方法如下图所示
这里我要简略的介绍两种文件选择的窗口 1、JFileChooser 2、FileDialog
JFileChooser 的通常用法如下:
JFileChooser chooser=new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//设置只能选择文件
chooser.setMultiSelectionEnabled(false);//设置文件不可多选
chooser.setFileFilter(new FileNameExtensionFilter("JPG文件", "jpg"));
int result=chooser.showOpenDialog(SaveInMySql.this);
if(result==JFileChooser.APPROVE_OPTION)//打开文件选择器
{
pf=new PictureFile();
File f=chooser.getSelectedFile();
String name=f.getName();
textField.setText(name);
pf.setPicture(f);
pf.setFileName(name);
}
效果如下图所示
如果想给其修饰一下,如下代码所示
JFileChooser chooser =new JFileChooser();
String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(chooser);//使设置得界面风格生效
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//设置只显示目录
chooser.showOpenDialog(frame);
FileDialog 的使用如下
FileDialog dialog=new FileDialog(this);
dialog.setVisible(true);
String path=dialog.getDirectory();
File f=new File(path);
File[] fs=f.listFiles(new java.io.FileFilter() {
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.getName().endsWith("tem"))
{
return true;
}
else
{
return false;
}
}
});
比较简单就不添加注释了