How to use FileDialog?
Asked Answered
M

3

26

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?

Manic answered 26/8, 2011 at 22:20 Comment(1)
See also FileDialogTest.Misquotation
P
50

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);
Previdi answered 12/3, 2013 at 12:8 Comment(1)
this helped alot, its much faster than a JFileChooser, shame it doesn't handle exceptions well, that null bit was tripping me up.Valency
G
13

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"));
Gastrovascular answered 21/3, 2015 at 6:23 Comment(4)
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
T
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.)

Telegram answered 26/8, 2011 at 22:23 Comment(1)
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.