【问题标题】:Cancel selecting a file within JFileChooser without closing the dialogue取消在 JFileChooser 中选择文件而不关闭对话框
【发布时间】:2013-05-08 16:52:53
【问题描述】:

我正在尝试使用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)。但是,它也会在之后立即关闭对话。

如果发生这种情况时对话保持打开状态,我更愿意这样做。有没有办法做到这一点?

【问题讨论】:

    标签: java swing joptionpane jfilechooser save-as


    【解决方案1】:

    覆盖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();
        }
    };
    

    【讨论】:

      【解决方案2】:

      如果 JFileChooser 不想覆盖该文件,您可以简单地再次重新打开。

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

      【讨论】:

        猜你喜欢
        • 2011-04-05
        • 2012-01-08
        • 2017-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多