gpt4 book ai didi

java - 在不关闭对话框的情况下取消在 JFileChooser 中选择文件

转载 作者:搜寻专家 更新时间:2023-11-01 03:07:51 24 4
gpt4 key购买 nike

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

这行得通,但是当我尝试添加另一个对话时遇到了问题。具体来说,我想使用 JOptionPane 创建一个“文件已存在”对话框如果用户试图创建与预先存在的文件同名的文件,则警告用户(这是许多程序中的常见功能)。对话提示"File <filename> already exists. Would you like to replace it?" (Yes/No) .如果用户选择"is",文件对象应该正常返回。如果用户选择“否”,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();
}
};

关于java - 在不关闭对话框的情况下取消在 JFileChooser 中选择文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16446109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com