该代码可用于检查非空/空格的AbsolutePath,但不适用于AbsolutePath仅为空白的情况。单击保存不执行任何操作,并且JFileChooser停留在showSaveDialog()中。
当用户尝试使用空白文件名保存文件时,我想显示JOptionPane错误消息。
try {
JFileChooser chooser = new JFileChooser("./");
FileNameExtensionFilter filter = new FileNameExtensionFilter("files (txt)", "txt");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
chooser.setSelectedFile(new File(fileName));
int value = chooser.showSaveDialog(this);
if (value == JFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().getAbsolutePath();
if (chooser.getSelectedFile().getName().trim().equals("")
|| !chooser.getSelectedFile().getName().endsWith(".txt")
|| chooser.getSelectedFile().getName().replaceAll(".txt", "").trim().equals("")) {
throw new IllegalArgumentException();
}
saveFile(filename);
}
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(this, "Fail! File was not saved", "Error", JOptionPane.ERROR_MESSAGE);
}
答案 0 :(得分:0)
Clicking save does nothing and the JFileChooser stays in showSaveDialog().
,如@camickr所说:this is the built in functionality of the JFileChooser and has nothing to do with your code. The file chooser doesn't close unless you enter a filename (and click Save) or use the Cancel button.
。