JFileChooser select directory but show files

后端 未结 9 1777
孤城傲影
孤城傲影 2020-12-11 00:49

I feel like there should be a simple way to do this but I can\'t figure it out. I have a JFileChooser that allows the user to select directories. I want to show all the file

9条回答
  •  感动是毒
    2020-12-11 01:29

    The solution of overriding approveSelection can be annoying for certain users.

    Sometimes, a user would just click on a file in a directory for no reason (even though she wants to select the directory and not the file). If that happens, the user would be (kind-a) stuck in the JFileChooser as the approveSelection will fail, even if she deselects the file. To avoid this annoyance, this is what I do:

    JFileChooser fileChooser = new JFileChooser();
    
    fileChooser.setFileSelectionMode(
            JFileChooser.FILES_AND_DIRECTORIES);
    
    int option = fileChooser.showDialog(null,
            "Select Directory");
    
    if (option == JFileChooser.APPROVE_OPTION) {
        File f = fileChooser.getSelectedFile();
        // if the user accidently click a file, then select the parent directory.
        if (!f.isDirectory()) {
            f = f.getParentFile();
        }
        System.out.println("Selected directory for import " + f);
    }
    

    Selecting the directory, even when the user selected a file results in a better usability in my opinion.

提交回复
热议问题