gpt4 book ai didi

java - 文件过滤器未出现在 Java swing 中的 JFileChooser 上

转载 作者:行者123 更新时间:2023-12-01 18:41:31 25 4
gpt4 key购买 nike

我有一个 JButton,需要打开特定扩展名的文件。简而言之,我定义了一个 JButton,向其中添加一个 Action 监听器,如果单击 JButton,该 Action 监听器将触发 JFileChooser。我想添加一个文件过滤器,以便只有扩展名为 .mpg 的文件才会显示在 JFileChooser 上。

编译没有显示错误,但在 Swing 时,JFileChooser 显示没有对可用文件的过滤(组合框中也没有出现选项“电影文件” - 仅显示“所有文件”)。简而言之,似乎 addChoosableFileFilter 没有任何效果。

我的代码是:

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"));

同样的命运。以上所有内容都在我的 swing 的 JFrame 的 JPanel 上。

我读过很多相关主题,但没有运气。

预先感谢您的评论。

最佳答案

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.

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());
}

试试这个。 Copied from here

关于java - 文件过滤器未出现在 Java swing 中的 JFileChooser 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19806517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com