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?

grb
  • 261
  • 1
  • 3
  • 3
  • 1
    See also [`FileDialogTest`](http://stackoverflow.com/questions/2914627/file-explorer-using-java-how-to-go-about-it/2914733#2914733). – trashgod Aug 27 '11 at 03:23

3 Answers3

49

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);
Salvatorelab
  • 11,614
  • 6
  • 53
  • 80
  • 1
    this helped alot, its much faster than a `JFileChooser`, shame it doesn't handle exceptions well, that `null` bit was tripping me up. – iKlsR Jun 03 '13 at 19:18
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"));
Neal Ehardt
  • 10,334
  • 9
  • 41
  • 51
  • 1
    Great solution but it won't work on Windows. https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html#setFilenameFilter%28java.io.FilenameFilter%29 – Keno Mar 24 '16 at 23:13
  • 1
    @KenoClayton True. I think the cross-platform solution is to use both `setFile` and `setFilenameFilter`. – Neal Ehardt Apr 08 '16 at 00:18
  • @NealEhardt Yes that's what I had to resort to. I'd simply check if it was windows and use the relevant function. – Keno Apr 08 '16 at 02:46
  • Found a "bug": setFilenameFilter() must be called before setVisible() to work! Tested on MAC "High Sierra". – trinity420 Jul 05 '18 at 17:29
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.)

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 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...) – ArtOfWarfare Dec 03 '13 at 12:53