FileDialog 在Windows下无法用FilenameFilter 且需要Frame
所有选择JFileChooser
JFileChooser fileChooser=new JFileChooser();//创建对象
fileChooser.setCurrentDirectory(new File("."));//当前显示目录 为工程目录
fileChooser.setAcceptAllFileFilterUsed(false); //是否显示所有文件
fileChooser.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
//返回true 表示显示 false不显示 getName返回该文件当前目录下所有的文件夹和文件
//判断该文件是文件夹
if(f.getName().endsWith(".java")||f.isDirectory()) {
return true;
}
return false;
}
@Override
public String getDescription() {
//设置文件栏的类型里文字
return "JAVA源程序(*.java)";
}
});
//监听事件获取选择文件
fileChooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File selectFile=fileChooser.getSelectedFile(); //选择文件
System.out.println(selectFile.getAbsolutePath());
}
});
fileChooser.showOpenDialog(null); //打开文件选择框
fileChooser.showSaveDialog(null);//保存文件选择框
}