在使用JFileChooser
保存文件时,我可能忽略了一些明显的API问题。我只能选择预先存在的文件进行保存,而不能输入新名称并将其保存。这是否可能使用JFileChooser
实现,或者我应该使用其他API?
以下是我尝试实现此功能的代码:
public static File getUserFile() {
final SaveFileChooser fc = new SaveFileChooser();
fc.setAcceptAllFileFilterUsed(false);
for(FileFilter ch : FileFilterUtils.getAllFilters()) {
fc.addChoosableFileFilter(ch);
}
int option = fc.showSaveDialog(JPad.getFrame());
if (option == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
}
return null;
}
public static class SaveFileChooser extends JFileChooser {
private static final long serialVersionUID = -8175471295012368922L;
@Override
public void approveSelection() {
File f = getSelectedFile();
if(f.exists() && getDialogType() == SAVE_DIALOG){
int result = JOptionPane.showConfirmDialog(JPad.getFrame(), "The file exists, overwrite?", "Existing file", JOptionPane.YES_NO_CANCEL_OPTION);
switch(result){
case JOptionPane.YES_OPTION:
super.approveSelection();
return;
case JOptionPane.NO_OPTION:
return;
case JOptionPane.CLOSED_OPTION:
return;
case JOptionPane.CANCEL_OPTION:
cancelSelection();
return;
}
}
}
}