【发布时间】:2012-11-13 10:46:18
【问题描述】:
我有一个函数应该获取在jfilechooser 的文本输入中键入的文件的路径并将其传递给String。问题是如果文件已经存在,我想检查覆盖。我确实知道如何执行此操作,但我的问题是,如果对 JOptionPane 回答 no,JFileChooser 无论如何都会关闭,因为保存按钮已经被操作.现在,我需要的是,如果答案是否,程序会返回JFileChooser,仍然提示输入名称。
请注意,我正在寻找一个有效的解决方案,我已经考虑过再次执行该函数,但是由于我的程序很大,因此这种解决问题的方法既费时又效率不高。
这是我的函数的代码,由于我不知道如何处理它,所以还没有完成。
`public String FileSavePath()throws NullPointerException
{
File f=null;
String theFilepath=null;
JFileChooser FileChooser = new JFileChooser();
if(FileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
theFilepath=FileChooser.getSelectedFile().getAbsolutePath();
f=FileChooser.getSelectedFile();
//System.out.println(theFile);
if(f.exists())
{
int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?",
"Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
if(result==JOptionPane.YES_OPTION)
{
return theFilepath;
}
else // here is what I should do if the user answers 'no' or cancels/closes the JOptionPane
}
else return null;
return theFilepath;
}`
【问题讨论】:
-
这是一个老问题,但它是我搜索结果中的第一个问题。可以在以下位置找到一个相当漂亮的解决方案:stackoverflow.com/a/3729157/589525
标签: java swing file jfilechooser overwrite