2017-06-20 74 views
-2

我在工具栏中有一个按钮,它必须保存我在Java中的JFrame中绘制的内容。它可以工作,但它目前充当“另存为”按钮。我试图在保存文件后覆盖文件而不显示对话框。有人可以帮我修复它吗?保存一个文件并在Java GUI中存在时覆盖它

我的代码:

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)"; 
      } 

} 

这是按钮本身与行动:

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

     res=this.fileChooser2.showSaveDialog(this); 
     if (res==JFileChooser.APPROVE_OPTION) 
     { 
     this.net.saveToFile(fileChooser2.getSelectedFile().getPath()+".xml"); 
     } 

    } 
+1

ev.getActionCommand()==“Save2” –

+0

'fileChooser2.showSaveDialog(this)'打开一个对话框。如果你不想这样做,那么实现一些逻辑,当第一次保存文件位置时存储文件的位置,如果存储位置,则保存到文件位置。 – Poohl

+1

您在FileFilter中显示JFileChooser对话框?这将造成严重破坏。 FileFilter的工作是根据是否显示文件来返回true或false。它不应该做任何事情。 – VGR

回答

1

你可以存储文件或至少路径一旦用户保存在第一个成员变量的文件中 时间。这将允许您识别绘图是否已保存并允许您覆盖它。

首先你需要一个字段来存储文件/文件路径:

private File savedFile; 

,那么你可以用它来覆盖它:

if (ev.getActionCommand().equals("Save2")) { 
    //Check if the drawing has already been saved, if not open the dialog 
    if(this.savedFile == null) { 
     fileChooser2.setDialogType(JFileChooser.SAVE_DIALOG); 
     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"); 
    } 
} 

我不知道如果这就是你想要什么做,我不知道你的this.net.saveToFile()方法确实做了什么,但我希望这可以帮助

+0

它的作品,它正是我想要的。谢谢! – Danny

+0

@Danny完美!没问题 – scsere

+0

'if(ev.getActionCommand()==“Save2”){'??真? –

相关问题