【问题标题】:How do I handle question marks or asterisks ('?' or '*') in JFileChooser save dialog?如何在 JFileChooser 保存对话框中处理问号或星号(“?”或“*”)?
【发布时间】:2021-06-07 22:41:59
【问题描述】:

首先我创建一个JFileChooser,然后调用showSaveDialog。如果用户在File Name 输入字段的任何位置输入问号? 或星号*,那么我会得到一些非常奇怪的行为。即,File Name 字段中用户输入的文本被复制到 Files of Type 字段中。

最小的可重现示例(没有导入):

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;
        }
    }
}

我已经在两台不同的 Windows 机器上复制了 Java 15 和 16 中的这种行为。在我的代码中,我确实在 path = jfc.getSelectedFile().getAbsolutePath(); 之前验证了用户提供的文本,但是无论我告诉系统做什么,这种行为都会发生,因此它必须在 JFileChooser 返回选项之前发生。

这里是发生了什么的屏幕截图:

如果用户输入了file_name??.txt,那么这就是Files of Type 字段中出现的内容。它再现了用户输入的文本。

最后,我确实找到了 2015 年另一位 SO 用户的两个相关帖子,但这似乎更复杂,我不想破坏他们的问题。

【问题讨论】:

    标签: java swing java-io jfilechooser


    【解决方案1】:

    如果 FileChooser 对文件列表进行动态过滤。

    如果用户输入“?”然后它将过滤所有文件名与单个字符。

    如果用户输入如下内容:“table*”,它将过滤所有以“table”开头的文件。

    如果用户输入如下内容:“table?”它将过滤所有以“table”开头的文件以及任何其他字符。

    BasicFileChooserUI 类中,当出现“*”或“?”时,FileFilter 会不断用GlobFilter 重置。在文件名中找到字符。

    我不知道如何禁用此功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      相关资源
      最近更新 更多