Danny Danny - 9 months ago 36
Java Question

Save a file and overwrite it when it exists in Java GUI

I have a button in a toolbar which has to save what I am drawing in a JFrame in Java. It works but it currently acts as a 'Save As' button. I am trying to make it overwrite the file once it is saved without showing a dialog. Can someone help me fix it?

My code:

JFileChooser fileChooser2;
this.fileChooser2 = new JFileChooser();
fileChooser2.addChoosableFileFilter(new TxtFilter2());


public class TxtFilter2 extends FileFilter

public boolean accept(java.io.File file)
if (file.isDirectory())
return true;

return (file.getName().endsWith("xml"));

public String getDescription()
return "Save (*.xml)";


This is the button itself with the action:

if (ev.getActionCommand()=="Save2")
fileChooser2.setDialogTitle("Save as XML file format");

if (res==JFileChooser.APPROVE_OPTION)


Answer Source

You could store the file or at least the path to the file in a member variable once the user saves for the first time. This would allow you to recognize whether the drawing has already been saved and allow you to overwrite it.

First you need a field to store the file/path:

private File savedFile;

then you can use it to overwrite it:

if (ev.getActionCommand() == "Save2") {
    //Check if the drawing has already been saved, if not open the dialog
    if(this.savedFile == null) {
        fileChooser2.setDialogTitle("Save as XML savedFile format");

        int res = this.fileChooser2.showSaveDialog(this);
        if (res == JFileChooser.APPROVE_OPTION) {
            final File selectedFile = fileChooser2.getSelectedFile();
            //Store the selected file in the member variable
            this.savedFile = selectedFile;
            this.net.saveToFile(selectedFile.getPath() + ".xml");
    }else {
        //Use the previously selected file and don't show the dialog
        this.net.saveToFile(this.savedFile.getPath() + ".xml");

I'm not sure if that's what you want to do and I don't know what exactly your this.net.saveToFile() method does but I hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download