JFileChooser chooser = new JFileChooser(); // Note: source for ExampleFileFilter can be found in FileChooserDemo, // under the demo/jfc directory in the Java 2 SDK, Standard Edition. ExampleFileFilter filter = new ExampleFileFilter(); filter.addExtension("jpg");//只看到jpg为后缀的文件 filter.addExtension("gif");//只看到gif为后缀的文件 filter.setDescription("JPG & GIF Images"); chooser.setFileFilter(filter); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//只看到文件夹 int returnVal = chooser.showOpenDialog(parent); if(returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); }
setFileSelectionMode public void setFileSelectionMode(int mode)Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories. The default is JFilesChooser.FILES_ONLY. Parameters: mode - the type of files to be displayed: JFileChooser.FILES_ONLY JFileChooser.DIRECTORIES_ONLY JFileChooser.FILES_AND_DIRECTORIES Throws: IllegalArgumentException - if mode is an illegal file selection mode See Also: getFileSelectionMode()
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("jpg");//只看到jpg为后缀的文件
filter.addExtension("gif");//只看到gif为后缀的文件
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//只看到文件夹 int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
public void setFileSelectionMode(int mode)Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories. The default is JFilesChooser.FILES_ONLY. Parameters:
mode - the type of files to be displayed:
JFileChooser.FILES_ONLY
JFileChooser.DIRECTORIES_ONLY
JFileChooser.FILES_AND_DIRECTORIES
Throws:
IllegalArgumentException - if mode is an illegal file selection mode
See Also:
getFileSelectionMode()
建议自己写一个。