4

を使用して「名前を付けて保存」ダイアログを実装しようとしていますJFileChooser。このダイアログでは、ユーザーがファイル名を入力して [保存] をクリックできるようにする必要があります。その時点で、新しいFileオブジェクトが返されて作成されます。

これは機能しますが、別のダイアログを追加しようとすると問題が発生します。JOptionPane具体的には、既存のファイルと同じ名前のファイルを作成しようとしている場合にユーザーに警告するために、「ファイルは既に存在します」ダイアログを作成したいと考えています (これは多くのプログラムで一般的な機能です)。ダイアログのプロンプトが表示され"File <filename> already exists. Would you like to replace it?" (Yes/No)ます。ユーザーが「はい」を選択すると、ファイル オブジェクトは通常どおり返されます。ユーザーが「いいえ」を選択した場合は、JFileChooser 開いたままにして、別のファイルの選択/作成を待つ必要があります。

問題は、選択をキャンセルして (ユーザーが「いいえ」を選択した場合) 、ダイアログを開いたままにする方法が見つからないことです。私はコードを持っています:

public void saveAs()
{
    if (editors.getTabCount() == 0)
    {
        return;
    }

    final JFileChooser chooser = new JFileChooser();

    chooser.setMultiSelectionEnabled(false);

    chooser.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent arg0)
        {
            File f =  chooser.getSelectedFile();

            if (f.exists())
            {
                int r = JOptionPane.showConfirmDialog(
                     chooser,
                     "File \"" + f.getName() +
                     "\" already exists.\nWould you like to replace it?",
                     "",
                     JOptionPane.YES_NO_OPTION);    

                //if the user does not want to overwrite
                if (r == JOptionPane.NO_OPTION)
                {
                    //cancel the selection of the current file
                    chooser.setSelectedFile(null);
                }
            }
        }
    });

    chooser.showSaveDialog(this);

    System.out.println(chooser.getSelectedFile());
}

ユーザーが「いいえ」を選択した場合、これはファイルの選択を正常にキャンセルします (つまり、ダイアログを閉じたときに選択されたファイルは ですnull)。ただし、その後すぐにダイアログも閉じます。

これが起こったときに対話が開かれたままであれば、私はそれを望んでいます. これを行う方法はありますか?

4

2 に答える 2

3

メソッドをオーバーライドしapproveSelection()ます。何かのようなもの:

JFileChooser chooser = new JFileChooser( new File(".") )
{
    public void approveSelection()
    {
        if (getSelectedFile().exists())
        {
            System.out.println("Do You Want to Overwrite File?");
            // Display JOptionPane here.  
            // if yes, super.approveSelection()
        }
        else
            super.approveSelection();
    }
};
于 2013-05-09T02:55:02.387 に答える