如何使用文件对话框?
我创建了一个界面,我想添加一个允许用户打开文件的函数。我正在使用AWT。我不明白如何使用FileDialog。你能给我一个例子或一个很好的链接来解释这一点吗?
我创建了一个界面,我想添加一个允许用户打开文件的函数。我正在使用AWT。我不明白如何使用FileDialog。你能给我一个例子或一个很好的链接来解释这一点吗?
一个完整的代码示例,带有文件筛选功能:
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);
通过@TheBronx来添加答案 - 对我来说,不适用于OS X。这有效:fd.setFile("*.txt");
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"));