How to use FileDialog?

∥☆過路亽.° 提交于 2019-11-27 03:47:50

问题


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?


回答1:


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



回答2:


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



回答3:


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.)



来源:https://stackoverflow.com/questions/7211107/how-to-use-filedialog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!