[java]java
import javax.swing.JFileChooser; web
public class FileChooser { this
public static void main(String[] args) spa
{ orm
JFileChooser fc = new JFileChooser("D:"); ip
//是否可多選 get
fc.setMultiSelectionEnabled(false); string
//選擇模式,可選擇文件和文件夾 it
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); io
// fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
// fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//設置是否顯示隱藏文件
fc.setFileHidingEnabled(true);
fc.setAcceptAllFileFilterUsed(false);
//設置文件篩選器
fc.setFileFilter(new MyFilter("java"));
fc.setFileFilter(new MyFilter("zip"));
int returnValue = fc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
//fc.getSelectedFile()
//fc.getSelectedFiles()
}
}
}
[java]
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class MyFilter extends FileFilter
{
private String ext;
public MyFilter(String extString)
{
this.ext = extString;
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension.toLowerCase().equals(this.ext.toLowerCase()))
{
return true;
}
return false;
}
public String getDescription() {
return this.ext.toUpperCase();
}
private String getExtension(File f) {
String name = f.getName();
int index = name.lastIndexOf('.');
if (index == -1)
{
return "";
}
else
{
return name.substring(index + 1).toLowerCase();
}
}
}