Search code examples
javaswingjava-iojfilechooser

How do I handle question marks or asterisks ('?' or '*') in JFileChooser save dialog?


First I create a JFileChooser and then call showSaveDialog. If a user enters a question mark ? or asterisk * anywhere in the File Name input field, then I get some very weird behavior. Namely, the user-entered text in the File Name field gets copied to the Files of Type field.

Minimal reproducible example (without imports):

public class ChooserTest {
    static String path;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JButton saveAsButton = new JButton("Save As");
        saveAsButton.addActionListener(e -> saveAs());
        frame.add(saveAsButton);
        frame.pack();
        frame.setVisible(true);
    }

    private static void saveAs() {
        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        int returnState = jfc.showSaveDialog(null);
        if(returnState == JFileChooser.APPROVE_OPTION) {
            path = jfc.getSelectedFile().getAbsolutePath();
            try {
                File f = new File(path);
                FileWriter out = new FileWriter(f);
                out.write("hello world");
                out.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        } else {
            return;
        }
    }
}

I've replicated this behavior in Java 15 and 16 on two different Windows machines. In my code, I do validate the user-provided text, right before path = jfc.getSelectedFile().getAbsolutePath();, but this behavior happens no matter what I tell the system to do, so it must be happening before the JFileChooser returns an option.

Here's a screenshot of what happens:

Here's a screenshot of what happens. If the user entered file_name??.txt, then that's what would appear in the Files of Type field. It reproduces the user-entered text.

Finally, I did find two related posts by another SO user from 2015, but that seemed to be more complex and I didn't want to clobber their question.


Solution

  • This if the FileChooser doing dynamic filtering on the file list.

    If the user enters "?" then it will filter all file names with a single character.

    if the user enters something like: "table*" it will filter all the files that start with "table".

    if the user enters something like: "table?" it will filter all the files the start with "table" plus any other character.

    In the BasicFileChooserUI class the the FileFilter keeps getting reset with the GlobFilter when either of the "*" or "?" characters is found in the file name.

    I don't know how to disable this feature.