1

a の textinput に入力されたファイルのパスを取得し、jfilechooserそれを a に渡す関数がありますString。問題は、ファイルが既に存在する場合に上書きを確認したいということです。私はこれを行う方法についての手がかりを持っていますが、私の問題は、保存ボタンがすでに操作されているため、にノーと答えた場合JOptionPane、とにかく閉じることです。JFileChooserここで必要なのは、答えがno の場合、プログラムが に戻り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;

    }`
4

1 に答える 1

2

ユーザーが許容できる応答を提供できるようになるまで、クエリをループに入れる必要があります...

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;

}
于 2012-11-25T23:42:04.467 に答える