How to use FileDialog?

后端 未结 3 535
旧巷少年郎
旧巷少年郎 2020-12-10 11:14

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

相关标签:
3条回答
  • 2020-12-10 11:19

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

    0 讨论(0)
  • 2020-12-10 11:25

    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);
    
    0 讨论(0)
  • 2020-12-10 11:33

    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"));
    
    0 讨论(0)
提交回复
热议问题