问题描述
我保存了一个文件,除了一个问题之外,它都能正常工作.当按下取消按钮时,文件副本将保存在java目录中.这仅在按下取消"按钮时发生,如果使用了保存"按钮,则文件最终会在用户选择的位置结束.我该如何阻止这种情况发生,所以当按下取消"按钮时,什么都不会保存在任何地方?
I have a file saved that works fine apart from one problem. When the cancel button is pressed a copy of the file is saved in the java directory. This only happens when the cancel button is pressed, if the save button is used the file ends up where the user selects. How can I stop this happening so when the cancel button is pressed nothing is saved anywhere?
下面是我的代码,感谢所有帮助.谢谢
My code is below, all help appreciated. Thanks
// Save dialog
private void savePlaylist() {
JFileChooser savePlaylistDialog = new JFileChooser();
savePlaylistDialog.setSelectedFile(new File(newPlaylistNameTxt.getText() + ".txt"));
savePlaylistDialog.showSaveDialog(playlistDialogs);
File savePlaylist = savePlaylistDialog.getSelectedFile();
try {
outFile = new PrintWriter(new FileWriter(savePlaylist));
outFile.println(newPlaylistInformationTxt.getText());
outFile.close();
// Plays a sound when play() is called (edited from Bombard)
try {
Clip saveButtonSound = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("Tri-tone.wav"));
saveButtonSound.open(ais);
saveButtonSound.start();
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}
推荐答案
savePlaylistDialog.showSaveDialog(playlistDialogs);
上面的方法调用返回一个int
.您需要检查其值-如果用户单击保存"按钮,它将返回JFileChooser.ACCEPTED_OPTION
.在这种情况下,您将获取返回值(可以接受/保存或取消),忽略它,然后继续将数据写入磁盘.
That method call above returns an int
. You need to check its value - if the user clicked on the Save button, it would return JFileChooser.ACCEPTED_OPTION
. In this case, you are taking the return value (which could be accepted/save or cancel), ignoring it, and proceeding to write the data to disk anyway.
这篇关于使用JFileChooser showSaveDialog保存的文件,即使在“取消"时也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!