如何使用文件对话框?

发布于 2024-12-01 19:11:00 字数 87 浏览 0 评论 0原文

我创建了一个界面,我想添加一个允许用户打开文件的功能。我正在使用AWT。我不明白如何使用 FileDialog。您能给我一个例子或一个很好的链接来解释这一点吗?

I created an interface and I'd like to add a function that allows user to open a file. I'm using AWT. I don't understand how to use FileDialog. Can you please give me an example or a good link that explain this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挖个坑埋了你 2024-12-08 19:11:01

完整的代码示例,带文件过滤:

FileDialog fd = new FileDialog(yourJFrame, "Choose a file", FileDialog.LOAD);
fd.setDirectory("C:\\");
fd.setFile("*.xml");
fd.setVisible(true);
String filename = fd.getFile();
if (filename == null)
  System.out.println("You cancelled the choice");
else
  System.out.println("You chose " + filename);

A complete code example, with file filtering:

FileDialog fd = new FileDialog(yourJFrame, "Choose a file", FileDialog.LOAD);
fd.setDirectory("C:\\");
fd.setFile("*.xml");
fd.setVisible(true);
String filename = fd.getFile();
if (filename == null)
  System.out.println("You cancelled the choice");
else
  System.out.println("You chose " + filename);
天赋异禀 2024-12-08 19:11:01

添加到 @TheBronx 的答案 - 对我来说, fd.setFile("*.txt"); 在 OS X 上不起作用。这有效:

fd.setFilenameFilter(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".txt");
    }
});

或者作为一个奇特的 Java 8 lambda:

fd.setFilenameFilter((dir, name) -> name.endsWith(".txt"));

To add to the answer by @TheBronx - for me, fd.setFile("*.txt"); is not working on OS X. This works:

fd.setFilenameFilter(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".txt");
    }
});

Or as a fancy Java 8 lambda:

fd.setFilenameFilter((dir, name) -> name.endsWith(".txt"));
听不够的曲调 2024-12-08 19:11:01

此处有一些代码示例,演示了如何使用它各种不同的任务。

也就是说,您可能需要退一步检查 awt 是否是最适合这里工作的任务。当然,使用它而不是像 swing / swt 这样的东西有充分的理由,但如果你刚刚开始,那么 Swing,IMO 将是一个更好的选择(有更多的组件,更多的教程,并且它是一个更广泛要求使用的库这些日子。)

There's a few code samples here that demonstrate how to use it for various different tasks.

That said, you might want to take a step back and check whether awt is the best task for the job here. There are valid reasons for using it over something like swing / swt of course, but if you're just starting out then Swing, IMO would be a better choice (there's more components, more tutorials and it's a more widely requested library to work with these days.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文