簡體   English   中英

取消選擇JFileChooser中的文件而不關閉對話框

[英]Cancel selecting a file within JFileChooser without closing the dialogue

我正在嘗試使用JFileChooser實現“另存為”對話框。 對話框應該讓用戶能夠輸入文件名並單擊“保存”,此時將返回並創建新的File對象。

這有效,但當我嘗試添加另一個對話時,我遇到了問題。 具體來說,我想使用JOptionPane創建一個“文件已存在”對話框,以警告用戶是否正在嘗試創建與預先存在的文件同名的文件(這是許多程序中的常見功能)。 對話框提示"File <filename> already exists. Would you like to replace it?" (Yes/No) "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 ),則成功取消文件的選擇。 但是,它也會在之后立即關閉對話。

如果對話在這種情況發生時保持開放,我更願意這樣做。 有沒有辦法做到這一點?

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

如果他們不想覆蓋文件,也許你可以再次簡單地重新打開JFileChooser。

該對話框將具有與之前相同的目錄,因此用戶無需再次導航。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM