4

我正在尝试使用JFileChooser. 该对话框应该让用户能够键入文件名并单击保存,此时File将返回并创建新对象。

这可行,但是当我尝试添加另一个对话时遇到了问题。具体来说,我想创建一个“文件已存在”对话框JOptionPane,如果他们试图创建一个与预先存在的文件同名的文件(这是许多程序中的一个常见功能),则使用 a 来警告用户。对话提示"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 回答
0

如果他们不想覆盖文件,也许您可​​以再次简单地重新打开 JFileChooser。

该对话框将具有与以前相同的目录,因此用户无需再次导航。

于 2013-05-08T17:00:00.497 回答