【问题标题】:JFileChooser: Preventing User from saving a file under existing nameJFileChooser:防止用户以现有名称保存文件
【发布时间】:2013-07-11 22:07:41
【问题描述】:

我正在使用 JFileChooser 来保存来自 textArea 的数据,并且我想阻止用户以现有名称保存他们的新文件。每次我执行代码时,它只会提示用户一次更改他们尝试保存的文件的名称。在输入新名称之前,我可以使用循环什么方法来阻止用户使用现有文件名?这是我目前所拥有的:

JButton OKSavebutton = new JButton("OK");
    OKSavebutton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            final JFileChooser fc = new JFileChooser();
            final int result = JOptionPane.showConfirmDialog(fc, "Save new Observation Well File?", "Save File", 
                    JOptionPane.OK_CANCEL_OPTION);
            fc.setCurrentDirectory(new File("C:/Users/281925/Desktop/mads/User Saved Internal Contamination Problem/Observation Wells"));

            FileNameExtensionFilter madsType = new FileNameExtensionFilter("MADS file (*.mads)", "mads");
            fc.setFileFilter(madsType);
            fc.addChoosableFileFilter(madsType);
            fc.setAcceptAllFileFilterUsed(false);

        int returnVal = fc.showSaveDialog(fc);
        File f = new File(fc.getSelectedFile()+".mads");

            switch(result){
            case JOptionPane.OK_OPTION:
                if (f.exists()){
                    int result1 = JOptionPane.showConfirmDialog(fc, "The file name exists. Please input new File name", "New File Name", 
                            JOptionPane.OK_CANCEL_OPTION);
                    fc.showSaveDialog(fc);
                }
                try{    
                    String fileExt = ".mads";
                        //create a buffered writer to write to a file
                        BufferedWriter out = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath() + fileExt));
                        out.write(textArea.getText());//write contents of the TextArea to the file
                        out.close();//close the file stream
                    }
                    catch(Exception e){  //catch any exceptions and write to the console
                        System.out.println(e.getMessage());
                    }

                return;
            case JOptionPane.CANCEL_OPTION:
                fc.cancelSelection();
                return;
                default:
                    return;
                    }

        }

    });

我已经做了两天了,我真的需要帮助!请,谢谢!

这是编辑后的代码。感谢@luk2302 的帮助。我确实需要稍微调整一下,但现在它就像一个魅力:)

int result1 = fc.showSaveDialog(fc);
        File f = new File(fc.getSelectedFile()+".mads");

        /* loop until the user entered a file that does not exist yet */
        while(f.exists()) { 

          result = JOptionPane.showConfirmDialog(fc, "The file name exists. Please input new File name", "New File Name", JOptionPane.OK_CANCEL_OPTION);

          if(result == JOptionPane.OK_OPTION){
             fc.showSaveDialog(fc);
         }
          /*Create new file and set it equal to f*/
          File f1 = new File(fc.getSelectedFile() + ".mads"); 
          f = f1;
        }

            /* return if user cancels */
        if(result == JOptionPane.CANCEL_OPTION) { 
            fc.cancelSelection();
            return;
          }
        /* if the user finally selected a non existing file do whatever needs to be done. */
        if (result == JOptionPane.OK_OPTION) {
          try { 
            String fileExt = ".mads";
            //create a buffered writer to write to a file
            BufferedWriter out = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath() + fileExt));
            out.write(textArea.getText());//write contents of the TextArea to the file
            out.close();//close the file stream
            } catch(Exception e){  //catch any exceptions and write to the console
            System.out.println(e.getMessage());
            }
          return;
          }

【问题讨论】:

    标签: java swing jfilechooser


    【解决方案1】:

    只需执行以下操作:

    /* loop until the user entered a file that does not exist yet */
    while(fc.getSelectedFile().exists()) { 
      result = JOptionPane.showConfirmDialog(fc, "The file name exists. Please input new File name", "New File Name", JOptionPane.OK_CANCEL_OPTION);
      fc.showSaveDialog(fc);
      /* return if user cancels */
      if(result == JOptionPane.CANCEL_OPTION) { 
        fc.cancelSelection();
        return;
      }
    }
    
    /* if the user finally selected a non existing file do whatever needs to be done. */
    if (result == JOptionPane.OK_OPTION) {
      try { 
        String fileExt = ".mads";
        //create a buffered writer to write to a file
        BufferedWriter out = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath() + fileExt));
        out.write(textArea.getText());//write contents of the TextArea to the file
        out.close();//close the file stream
      } catch(Exception e){  //catch any exceptions and write to the console
        System.out.println(e.getMessage());
      }
      return;
    }
    

    还请注意,您分配了从未使用过的int returnVal = fc.showSaveDialog(fc);,而是在其余代码中使用result 的值。所以将变量重命名为`int result = fc.showSaveDialog(fc);`

    【讨论】:

    • 感谢您的帮助!我确实需要对其进行一些调整,但现在它完成了我需要它做的事情。查看我修改后的代码。
    • 很高兴您发布工作代码,很高兴您理解了总体思路。
    • @B.Harper,无需使用 while 循环并继续重新显示保存对话框。我敢肯定,当你使用这种方法时,你会得到很多闪烁。
    • @camickr 为什么? showConfirmDialogshowSaveDialog“暂停”程序,直到用户以某种方式采取行动,完全没有闪烁。
    • @luk2302,当我说闪烁时,我的意思是保存对话框被隐藏,选项窗格显示,然后再次显示保存对话框。循环重复。通常选项窗格出现在保存对话框上方,并且只有在用户完成选择文件名后才会关闭保存对话框。
    【解决方案2】:

    只需重写 JFileChooser 的approveSelection 方法

    JFileChooser fileChooser = new JFileChooser()
            {
                @Override
                public void approveSelection()
                {
                    File f = getSelectedFile();
                    if (f.exists() && getDialogType() == SAVE_DIALOG)
                    {
                        int result = JOptionPane.showConfirmDialog(this,
                                                                   String.format("%s already exists.%n Overwrite?", f.getName()),
                                                                   "File already exists", JOptionPane.YES_NO_OPTION);
    
                        switch (result)
                        {
                            case JOptionPane.YES_OPTION:
                                super.approveSelection();
                                return;
                            case JOptionPane.NO_OPTION:
                                return;
                            case JOptionPane.CLOSED_OPTION:
                                return;
                            case JOptionPane.CANCEL_OPTION:
                                cancelSelection();
                                return;
                        }
                    }
                    super.approveSelection();
                }
            };
    

    【讨论】:

      【解决方案3】:

      重写approveSelection() 方法以防止/确认这一点:

      import java.awt.event.*;
      import java.io.*;
      import javax.swing.*;
      import javax.swing.plaf.basic.*;
      
      public class FileChooserSave
      {
          public static void main(String[] args)
          {
              final JFileChooser chooser = new JFileChooser( new File(".") )
              {
                  public void approveSelection()
                  {
                      if (getSelectedFile().exists())
                      {
                          System.out.println("Do You Want to Overwrite File?");
                      }
                      else
                          super.approveSelection();
                  }
              };
      
              chooser.addActionListener(new ActionListener()
              {
                  public void actionPerformed(ActionEvent e)
                  {
                      System.out.println(e);
                  }
              });
      
              chooser.setSelectedFile( new File("something.rob") );
              int returnVal = chooser.showSaveDialog(null);
      
      
              if(returnVal == JFileChooser.APPROVE_OPTION)
              {
                 System.out.println(chooser.getSelectedFile() );
              }
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-26
        • 1970-01-01
        • 2013-09-12
        • 2011-02-24
        • 2015-04-17
        • 1970-01-01
        • 2011-02-01
        • 2012-02-10
        相关资源
        最近更新 更多