我有一个函数应该获取在jfilechooser的textinput中键入的文件的路径,并将其传递给String。问题是我要检查是否已存在该文件的覆盖。我确实知道如何执行此操作,但是我的问题是,如果对JOptionPane回答否,则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;

    }`

最佳答案

您需要将查询放入循环中,直到用户可以为您提供可接受的响应为止。

public String FileSavePath() throws NullPointerException {

    boolean acceptable = false;
    String theFilepath = null;

    do {
        theFilepath = null
        File f = 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) {
                    acceptable = true;
                }
            } else {
                acceptable = true;
            }
        } else {
            acceptable = true;
        }
    } while (!acceptable);

    return theFilepath;

}

09-10 08:34
查看更多