返回特定对话框

时间:2009-01-30 23:39:22

标签: java swing

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

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

所以我有一个JFileChooser会提示用户覆盖:yes,no,cancel

如果没有被选中,它应该返回到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;
}

1 个答案:

答案 0 :(得分:0)

从这条线开始怎么样:

int returnVal = saveFile.showOpenDialog(null);

再次,当你应该回到JFileChooser?我假设同一个文件选择器 会再次显示其打开的对话框吗?