问题描述
(预先感谢!如果您需要更多信息,请告诉我.底部的示例代码.)
(Thanks in advance! Please let me know if you need more info. Sample code at the bottom.)
我要解决的问题:
我试图通过使用javax.swing.filechooser.FileFilter对象来使此JFileChooser对象仅显示目录(而不显示文件),该对象在被accept(文件文件)重写的方法中具有此对象:.但是,至少在我的Mac上,这似乎并不能阻止文件与目录一起显示(它确实可以防止不使用setFileSelectionMode()方法选择文件).
I'm trying to get this JFileChooser object to display only directories (and not files), through the use of a javax.swing.filechooser.FileFilter object that has this in the accept(File file) overridden method: return file.isDirectory();
. However, at least on my mac, it doesn't seem to prevent files from being displayed along with the directories (it does prevent files from being selected without using the setFileSelectionMode() method).
问题
我错过了什么吗?如果没有,以前有没有人遇到过?
Am I missing something? If not, has anyone ever encountered this before?
我的理解/假设:
- 当您将javax.swing.filechooser.FileFilter对象传递到JFileChooser的
setFileFilter()
方法中时,魔术应该会发生. - 似乎我的带有setFileFilter()的JFileChooser像使用
setSelectionMode( JFileChooser.DIRECTORIES_ONLY );
- The magic should happen when you pass in a javax.swing.filechooser.FileFilter object into the JFileChooser's
setFileFilter()
method. - Seems like my JFileChooser with setFileFilter() is behaving like its using of
setSelectionMode( JFileChooser.DIRECTORIES_ONLY );
代码
import java.io.File;
import javax.swing.filechooser.FileFilter;
// inside a method that's adding this to a JPanel
_fileChooser = new JFileChooser( "." );
_fileChooser.setControlButtonsAreShown( false );
_fileChooser.setFileFilter( new FolderFilter() );
// _fileChooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
_panelMidLeft.add( _fileChooser );
// an inner class, defined somewhere else in the class
private class FolderFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept( File file ) {
return file.isDirectory();
}
@Override
public String getDescription() {
return "We only take directories";
}
}
谢谢!
亚历克斯
推荐答案
您的代码对我有用.我的 SSCCE :
Your code works for me. My SSCCE:
import java.io.File;
import javax.swing.JFileChooser;
public class ShowDirectoriesOnly {
public static void main(String[] args) {
JFileChooser fileChooser = new JFileChooser( "." );
fileChooser.setControlButtonsAreShown( false );
fileChooser.setFileFilter( new FolderFilter() );
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.showOpenDialog(null);
}
private static class FolderFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept( File file ) {
return file.isDirectory();
}
@Override
public String getDescription() {
return "We only take directories";
}
}
}
如果您仍然遇到问题,最好的办法就是创建自己的 SSCCE 来证明您的问题.
If you're still having problems, your best is to create your own SSCCE that demonstrates your problem.
编辑
使用JDK1.7在OS X下的外观截图
Screenshot on how it looks under OS X with JDK1.7
这篇关于具有过滤器的Java JFileChooser据称只能显示目录,但无法仅显示目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!