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