【问题标题】:Why my "Save" button doesn't work?为什么我的“保存”按钮不起作用?
【发布时间】:2013-11-30 07:39:43
【问题描述】:

我的程序中有一个最大的问题。我创建了保存按钮,但如果 .txt 文件是新的,它会保存(然后该按钮执行“另存为”功能)。但是当我打开文件时,然后输入一些东西并尝试保存它并没有保存:S。谁能帮帮我?

代码如下:

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) {

    }
}

【问题讨论】:

  • 你可能吞下了异常吗?永远不要那样做,处理它。
  • 当您尝试保存已打开的文件时,您确定saveFile 会执行吗?我假设,这个 if 语句 if(currentFile == null) 不会让你的方法被调用。
  • 什么是field?为了尽快获得更好的帮助,请发布SSCCE。在这种情况下,如果字段是JTextComponent,它将有一个专门用于保存内容的方法。另外,将catch (Exception e) { .. 形式的代码更改为catch (Exception e) { e.printStackTrace(); // very informative! ..

标签: java actionlistener savechanges


【解决方案1】:

当 currentFile != null 时,您没有处理,我假设您尝试保存已具有文件名的文件时就是这种情况。

做这样的事情:

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

移动

saveFile(currentFile, field.getText());

进入上面if else的else部分。

目前您在if(currentFile == null) 中拥有它,这不是您在此处调用saveFile(null, field.getText()) 的正确位置。


还有

catch(Exception e) {

}

很糟糕,永远不要吞下异常并且什么都不做,你永远不会知道异常是否发生,只是什么都不会发生。

【讨论】:

  • 非常感谢你:)。但它不保存我的“Enters”是不是很好?
  • 你是什么意思,它不保存你的“Enters”,你的“Enters”是什么意思?
  • 它没有保存我由“Enter”按钮创建的新行
  • 您需要解析文本字段的值以找到换行符并将它们添加到您的输出文件中。网上有很多这样的例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 2010-10-30
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多