在 Java 中需要带有文件类型过滤器的 FileDialog

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1241984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:46:54  来源:igfitidea点击:

Need FileDialog with a file type filter in Java

javaswingawtfiledialog

提问by Morinar

I have a JDialog with a button/textfield for the user to select a file. Here's the code:

我有一个带有按钮/文本字段的 JDialog,供用户选择文件。这是代码:

FileDialog chooser = new FileDialog(this, "Save As", FileDialog.SAVE );
String startDir = saveAsField.getText().substring( 0, saveAsField.getText().lastIndexOf('\') );
chooser.setDirectory(startDir);
chooser.setVisible(true);
String fileName = chooser.getFile();

My problem is that instead of seeing an All Files filter, I want to provide a custom filter, e.g. for Word docs or something. I setup a custom FilenameFilter using setFilenameFilter(), but it didn't seem to work. I did notice that it says in the docs that the custom filter doesn't work in Windows (this runs in Windows XP/Vista/7). Here was my implementation of the filter:

我的问题是,不是看到所有文件过滤器,我想提供一个自定义过滤器,例如 Word 文档或其他东西。我使用 setFilenameFilter() 设置了自定义 FilenameFilter,但它似乎不起作用。我确实注意到它在文档中说自定义过滤器在 Windows 中不起作用(这在 Windows XP/Vista/7 中运行)。这是我对过滤器的实现:

chooser.setFilenameFilter( new geFilter() );
public class geFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return name.endsWith( ".doc" ) || name.endsWith( ".docx" );
    }
}

Am I doing something wrong here? Also, I want a description to appear in the box, like "Microsoft Word (*.doc *.docx)" but I'm not sure how to do that.

我在这里做错了吗?另外,我希望在框中显示描述,例如“Microsoft Word (*.doc *.docx)”,但我不知道该怎么做。

Any and all help is appreciated.

任何和所有的帮助表示赞赏。

回答by Adam Batkin

AWT isn't really the preferred way of writing Java GUI apps these days. Sun seems to have mostly abandoned it. The two most popular options are Swing and SWT. So I think they didn't really develop the APIs very extensively to add modern features. (err, to answer your question: No you don't appear to be able to do that with AWT)

如今,AWT 并不是编写 Java GUI 应用程序的首选方式。Sun 似乎基本上已经放弃了它。两个最流行的选项是 Swing 和SWT。所以我认为他们并没有真正广泛地开发 API 来添加现代功能。(错误,回答你的问题:不,你似乎不能用 AWT 做到这一点)

Swing has the advantage that it is truly write-once-run-anywhere and it can look exactly the same everywhere. There are Look & Feels that try to make Swing look native, some are better than others (Mac isn't terrible, Windows is okay, GTK isn't). Still, if you want an app that really looks and acts EXACTLY the same everywhere, Swing will let you do that. Plus it runs out-of-the-box without any extra libraries. Performance isn't great.

Swing 的优势在于它真正实现了一次编写,随处运行,并且在任何地方看起来都完全一样。有一些外观和感觉试图使 Swing 看起来很原生,有些比其他更好(Mac 并不糟糕,Windows 还可以,GTK 不是)。尽管如此,如果您想要一个在任何地方看起来和行为都完全相同的应用程序,Swing 可以让您做到这一点。此外,它开箱即用,无需任何额外的库。性能不是很好。

Swing's JFileChooserwill let you do what you want. Create a subclass of FileFilterand call setFileFilteron the JFileChooser.

Swing 的JFileChooser会让你做你想做的事。创建的子类的FileFilter,并呼吁setFileFilterJFileChooser

SWT takes the write-once-run-anywhere to the opposite extreme. You still have one codebase that you write against, but it actually uses the native widgets on each platform so it generally looks like a native app (not perfect everywhere, but still impressive). It's fast and pretty reliable in my experience. Eclipse (and other high profile software) uses SWT so it's in pretty heavy use. But it does require platform-specific JARs and DLLs.

SWT 将一次写入随处运行的情况带到了相反的极端。你仍然有一个你编写的代码库,但它实际上在每个平台上使用本机小部件,所以它通常看起来像一个本机应用程序(并非处处完美,但仍然令人印象深刻)。根据我的经验,它快速且非常可靠。Eclipse(和其他知名软件)使用 SWT,因此它的使用非常频繁。但它确实需要特定于平台的 JAR 和 DLL。

回答by dfa

since you are using JDialog, that is a swing class why not using JFileChooser?

既然您使用的是 JDialog,那是一个摆动类,为什么不使用JFileChooser呢?

 JFileChooser fc = new JFileChooser("C:\");
 fc.setFileFilter(new FileNameExtensionFilter("Microsoft Word (*.doc, *.docx)", "doc", "docx"));

FileNameExtensionFilteris a nice Java 6 class that does exactly what you want.

FileNameExtensionFilter是一个很好的 Java 6 类,它完全符合您的要求。

回答by ceklock

I am also trying to do that. I want to use FileDialog instead of JFileChooser.

我也在努力做到这一点。我想使用 FileDialog 而不是 JFileChooser。

I found the answer here: http://www.rgagnon.com/javadetails/java-0247.html

我在这里找到了答案:http: //www.rgagnon.com/javadetails/java-0247.html

He says that "on the Win platform, the setFilenameFilter method don't work. We must use the setFile method instead to set a filter."

他说“在 Win 平台上,setFilenameFilter 方法不起作用。我们必须改用 setFile 方法来设置过滤器。”

There is source code at the specified link.

指定链接处有源代码。

I tested and it works:

我测试过,它有效:

FileDialog fd = new FileDialog((Frame) null, "Save File", FileDialog.SAVE);
fd.setFile("*.txt");
fd.setVisible(true);

String file = fd.getFile();
System.out.println(file);
System.exit(0);

回答by ceklock

If you ever use JavaFX 2, the FileChooserclass will do exactly what you need without any of JFileChooser/FileDialog problems. You can also embed JavaFX 2 components inside Swing applications, but you need JavaFX runtime.

如果您曾经使用过JavaFX 2,那么FileChooser类将完全满足您的需求,而不会出现任何 JFileChooser/FileDialog 问题。您还可以在 Swing 应用程序中嵌入 JavaFX 2 组件,但您需要JavaFX 运行时

Example:

例子:

    FileChooser fc = new FileChooser();
    FileChooser.ExtensionFilter filter;
    filter = new FileChooser.ExtensionFilter("Text files (*.txt)", "*.txt");
    fc.getExtensionFilters().add(filter);
    File f = fc.showOpenDialog(primaryStage);
    System.out.println(f);

回答by stevpan

You can call the native Windows Filedialog (CFileDialog) with JNI. Filters can be set for CFileDialog easily.

您可以使用 JNI 调用本机 Windows 文件对话框 (CFileDialog)。可以轻松地为 CFileDialog 设置过滤器。

I wrote a simple wrapper class for CFileDialog several months ago, If you are interested, you can get the source and binary from

几个月前我为 CFileDialog 写了一个简单的包装类,如果你有兴趣,你可以从

Xfiledialog project on google code

谷歌代码上的 Xfiledialog 项目

回答by Pixel

Just use setFilenameFiltermethod of the FileDialoginstance fd:

只需使用实例的setFilenameFilter方法:FileDialogfd

            fd.setFilenameFilter(new FilenameFilter()
                            {
                                @Override
                                public boolean accept(File file, String s)
                                {
                                    // enter code to return TRUE or FALSE here
                                    return s.contains(".txt");
                                }
                            });