简体   繁体   English

为什么我的“保存”按钮不起作用?

[英]Why my “Save” button doesn't work?

I have one of the biggest problem in my program. 我的程序中存在一个最大的问题。 I've created Save button, but it saves if the .txt file is new (Then that button does "SaveAs" function). 我已经创建了“保存”按钮,但如果.txt文件是新的,则会保存(然后该按钮执行“SaveAs”功能)。 But when I open file, then type something and trying to save and it's not saving :S. 但是当我打开文件,然后键入一些内容并尝试保存并且它不会保存:S。 Can anyone help me? 谁能帮我?

Here's the code: 这是代码:

fileSave.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if(currentFile == null) {
            int saveResult = fileSelect.showSaveDialog(null);
            if(saveResult == fileSelect.APPROVE_OPTION) {
                saveFile(fileSelect.getSelectedFile(), field.getText());            
            } else {
                saveFile(currentFile, field.getText());
            }
        }
    }
});

public void saveFile(File file, String contents) {
    BufferedWriter writer = null;
    String filePath = file.getPath();
    if(!filePath.endsWith(".txt")) {
        filePath += ".txt";
    }

    try {
        writer = new BufferedWriter(new FileWriter(filePath));
        writer.write(contents);
        writer.close();
        field.setText(contents);
        setTitle("Editex - " + filePath);
        currentFile = file;
    } catch (Exception e) {

    }
}

You aren't handling when currentFile != null, which is what I am assuming is the case when you are trying to save a file that already has a Filename. 当currentFile!= null时,您没有处理,这是我在假设您尝试保存已具有文件名的文件时的情况。

Do something like this: 做这样的事情:

if(currentFile == null) {
    // Handle if new file
} else {
    // Handle an existing file
}

Move 移动

saveFile(currentFile, field.getText());

into the else part of the above if else. 进入上面的其他部分if else。

At the moment you have it within the if(currentFile == null) , and this isn't the correct place as you are calling saveFile(null, field.getText()) here. 目前你在if(currentFile == null)有它,并且这不是正确的地方,因为你在这里调用saveFile(null, field.getText())


Also

catch(Exception e) {

}

is bad, never swallow an exception and do nothing with it, you will never know if an exception happens or not, just nothing will happen. 是不好的,永远不会吞下一个例外并且不做任何事情,你永远不会知道是否发生了异常,只是什么都不会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM