问题描述
首先我创建一个 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 用户的两篇相关帖子,但这似乎更复杂,我不想打扰他们的问题。
解决方法
如果 FileChooser 对文件列表进行动态过滤。
如果用户输入“?”然后它会用一个字符过滤所有文件名。
如果用户输入类似“table*”的内容,它将过滤所有以“table”开头的文件。
如果用户输入类似:“table?”它将过滤所有以“table”开头的文件加上任何其他字符。
在 BasicFileChooserUI
类中,当出现“*”或“?”时,FileFilter 不断使用 GlobFilter
进行重置。在文件名中找到字符。
我不知道如何禁用此功能。