文件筛选器未出现在Java swing中的JFileChooser上 [英] File Filter does not appear on JFileChooser in Java swing
问题描述
我有一个JButton,需要打开特定扩展名的文件.简而言之,我定义了一个JButton,如果单击JButton,则向其添加一个动作侦听器,该动作侦听器将触发JFileChooser.我想添加一个文件过滤器,以便仅扩展名.mpg的文件将显示在JFileChooser上.
I have a JButton that needs to open a file of a specific extension. In brief, I define a JButton add an actionlistener to it that fires a JFileChooser, if JButton is clicked. I want to add a file filter so that only files of extension .mpg will be shown on the JFileChooser.
该编译没有显示任何错误,但是JFileChooser在显示时没有显示对可用文件的过滤(也不会出现组合框中的电影文件"选项-仅显示所有文件").用两个词来说,addChoosableFileFilter
似乎毫无作用.
The compilation shows no errors, but on the swing the JFileChooser shows no filtering of the available files (nor the option 'Movie files' in the combobox appears - just 'All files'). In two words, it seems that addChoosableFileFilter
has no effect whatsoever.
我的代码是:
final JFileChooser jfc = new JFileChooser(moviedir);
//add File Filter
jfc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Movie files (*.mpg)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {return true;}
else {return f.getName().toLowerCase().endsWith(".mpg");}
}
});
我也尝试过
jfc.addChoosableFileFilter(new FileNameExtensionFilter("Movie files", "mpg"));
有着相同的命运.以上所有内容都在我的JFrame的JPanel上.
with the same fate. All the above are on JPanel of a JFrame of my swing.
我已经阅读了许多相关的主题,但是没有运气.
I 've read many related threads but no luck.
预先感谢您的评论.
推荐答案
JFileChooser提供了一种简单的机制,供用户选择 文件.有关使用JFileChooser的信息,请参见如何使用文件. 选择器,《 Java教程》中的一节.
JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser, see How to Use File Choosers, a section in The Java Tutorial.
以下代码为用户的住所弹出一个文件选择器 仅显示.jpg和.gif图片的目录:
The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
尝试一下. 从此处复制
这篇关于文件筛选器未出现在Java swing中的JFileChooser上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!