【问题标题】:Return to a specific dialog返回特定对话框
【发布时间】:2009-01-30 23:39:22
【问题描述】:

我正在编写一个非常简单的文本编辑器,但遇到了一个小问题。代码如下

保存文件,当文件存在时,会提示用户覆盖、取消或不覆盖(可选择重试)。

所以我有一个 JFileChooser 会提示用户覆盖:是,否,取消

在没有被选中的情况下,它应该返回到 JFileChoose 对话框,但我只是不知道如何。谁能帮我解决这个问题?取消和是选项没有任何问题(据我所知,尚未深入测试)

String contents = textArea.getText();
if (openPath != null) {
    savePath = openPath;                    
} else if (saveAsPath != null) {
    savePath = saveAsPath;
} else if (savePath != null) {
    savePath = savePath;
} else if (openPath == null) {
    JFileChooser saveFile = new JFileChooser();
    int returnVal = saveFile.showOpenDialog(null);
    if (returnVal == saveFile.APPROVE_OPTION) {
        savePath = saveFile.getSelectedFile();
        if (!savePath.exists()) {
        FileWriter fstream = new FileWriter (savePath);
        BufferedWriter saveWrite = new BufferedWriter(fstream);
        saveWrite.write(contents);
        saveWrite.close();
        } else if (savePath.exists()) {
            JOptionPane overwritePrompt = new JOptionPane();
            Object[] options = {"Yes","No","Cancel"};
            int n = JOptionPane.showOptionDialog(overwritePrompt,
               "Already exists. Overwrite?","Overwrite File?", 
               JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE,
               null,options,options[2]);
        if (n == 0) {
        FileWriter fstream = new FileWriter(saveAsPath);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(contents);
        out.close();
        } else if (n == 1) {
            savePath = null;
            openPath = null;
            saveAsPath = null;
            return; // should return to JFileChooser
        } else {
                savePath = null;
            openPath = null;
            saveAsPath = null;
            return;
        }
    }
} else {
    return;
}

【问题讨论】:

    标签: java swing


    【解决方案1】:

    从这一行重新开始怎么样:

    int returnVal = saveFile.showOpenDialog(null);
    

    再次,您应该何时返回 JFileChooser?我假设相同的文件选择器 会再次显示其打开的对话框吗?

    【讨论】:

    • 哇,太糟糕了。谢谢人 - 破坏该代码感觉很可怕,但你是对的。我从来没有深入研究过 JChooseFile - 只是举例
    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 2012-05-22
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多