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?
How to use FileDialog?
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);
this helped alot, its much faster than a
JFileChooser
, shame it doesn't handle exceptions well, that null
bit was tripping me up. –
Valency 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"));
Great solution but it won't work on Windows. docs.oracle.com/javase/7/docs/api/java/awt/… –
Sande
@KenoClayton True. I think the cross-platform solution is to use both
setFile
and setFilenameFilter
. –
Gastrovascular @NealEhardt Yes that's what I had to resort to. I'd simply check if it was windows and use the relevant function. –
Sande
Found a "bug": setFilenameFilter() must be called before setVisible() to work! Tested on MAC "High Sierra". –
Gonadotropin
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.)
All three of the code samples that that link leads to are the exact same... (just saying, if they look similar, you're not crazy...) –
Radiolarian
© 2022 - 2024 — McMap. All rights reserved.
FileDialogTest
. – Misquotation