1

我怎么能删除一个文件JFileChooserDelete我知道,自从用本机编写以来,AWT 可以选择使用简单的按钮从中删除文件。

但是如果我想删除文件JFileChooser怎么办?当我试图删除时,我得到一个异常,文件正在被另一个程序访问,因此无法删除

在这种情况下我想问的两个问题是..

问题

  1. 是否有任何黑客可以删除文件JFileChooser
  2. 为什么我在删除时没有得到另一个程序正在访问文件FileDialog。是因为它是用本机代码编写的吗?

任何帮助表示赞赏。提前致谢。

4

3 回答 3

2

是的!我知道了!我什至JFileChooser在文件被删除后更新了。

更新

根据 Rob Camick 先生的建议,jf.getUI().rescanCurrentDirectory(jf)添加了删除多个文件并修改jf.rescanCurrentDirectory()和删除多余文件的功能。PropertyChangeListener

/*
* @see http://stackoverflow.com/a/17622050/2534090
* @author Gowtham Gutha
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
class DeleteThroughJFileChooser extends JFrame
{
JButton jb;
JFileChooser jf;
File[] selectedFiles;
    public DeleteThroughJFileChooser()
    {
        // Create and show GUI
        createAndShowGUI();
    }

    private void createAndShowGUI()
    {
        // Set frame properties
        setTitle("Delete through JFileChooser");
        setLayout(new FlowLayout());
        setSize(400,400);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Create JFileChooser
        jf=new JFileChooser();

        // Allow multiple selection
        jf.setMultiSelectionEnabled(true);

        // Create JButton
        jb=new JButton("Open JFileChooser");

        // Add ActionListener to it
        jb.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // Show the file chooser
                showFileChooser();
            }
        });

        // Register the delete action
        registerDelAction();

        // Add JButton jb to JFrame
        add(jb);
    }

    private void showFileChooser()
    {
        // Show the open dialog
        int op=jf.showOpenDialog(this);
    }

    private void registerDelAction()
    {
        // Create AbstractAction
        // It is an implementation of javax.swing.Action
        AbstractAction a=new AbstractAction(){

            // Write the handler
            public void actionPerformed(ActionEvent ae)
            {
                JFileChooser jf=(JFileChooser)ae.getSource();
                try
                {

                // Get the selected files
                selectedFiles=jf.getSelectedFiles();

                    // If some file is selected
                    if(selectedFiles!=null)
                    {
                        // If user confirms to delete
                        if(askConfirm()==JOptionPane.YES_OPTION)
                        {

                        // Call Files.delete(), if any problem occurs
                        // the exception can be printed, it can be
                        // analysed
                        for(File f:selectedFiles)
                        java.nio.file.Files.delete(f.toPath());

                        // Rescan the directory after deletion
                        jf.rescanCurrentDirectory();
                        }
                    }
                }catch(Exception e){
                    System.out.println(e);
                }
            }
        };

        // Get action map and map, "delAction" with a
        jf.getActionMap().put("delAction",a);

        // Get input map when jf is in focused window and put a keystroke DELETE
        // associate the key stroke (DELETE) (here) with "delAction"
        jf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"),"delAction");
    }

    public int askConfirm()
    {
        // Ask the user whether he/she wants to confirm deleting
        // Return the option chosen by the user either YES/NO
        return JOptionPane.showConfirmDialog(this,"Are you sure want to delete this file?","Confirm",JOptionPane.YES_NO_OPTION);
    }

    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new DeleteThroughJFileChooser();
            }
        });
    }
}
于 2013-07-12T18:52:05.663 回答
0

为什么要从选择器中删除文件?

使用 jfilechooser 将文件名和位置存储作为变量获取。关闭文件 jfilechooser。然后删除文件。

import java.io.File;

public class DeleteFileExample
{
public static void main(String[] args)
{   
    try{

        File file = new File("c:\\logfile20100131.log");

        if(file.delete()){
            System.out.println(file.getName() + " is deleted!");
        }else{
            System.out.println("Delete operation is failed.");
        }

    }catch(Exception e){

        e.printStackTrace();

    }

}
}

此外,如果您希望 jfilechooser 本身具有该功能,我发现此代码可能会很有用。从这里。要运行它,您还需要This。摆动文件

import darrylbu.util.SwingUtils;
import java.awt.Container;
import java.awt.Point;
import java.awt.event.*;
import javax.swing.*;

public class FileChooserDeleteMenu {

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {
        new FileChooserDeleteMenu().makeUI();
      }
    });
  }

  public void makeUI() {
    final JFileChooser chooser = new JFileChooser();
     final JList list = SwingUtils.getDescendantOfType(JList.class, chooser, "Enabled",    true);
    JPopupMenu popup = list.getComponentPopupMenu();
    JMenuItem item = new JMenuItem("Delete");
    item.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        if (chooser.getSelectedFile() != null) {
          JOptionPane.showConfirmDialog(chooser,
                  "Delete " + chooser.getSelectedFile().getAbsolutePath() + "?",
                  "Confirm delete",
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
        }
         }
   });
      popup.add(item);

    final MouseListener listener = new MouseAdapter() {

      @Override
      public void mousePressed(MouseEvent e) {
        Point p = e.getPoint();
        if (e.getSource() == list) {
          list.setSelectedIndex(list.locationToIndex(p));
        } else {
          JTable table = (JTable) e.getSource();
          if (table.columnAtPoint(p) == 0) {
            int row = table.rowAtPoint(p);
            table.getSelectionModel().setSelectionInterval(row, row);
          }
        }
      }
    };
    list.addMouseListener(listener);

    final Container filePane =     SwingUtilities.getAncestorOfClass(sun.swing.FilePane.class, list);

    filePane.addContainerListener(new ContainerAdapter() {

      @Override
      public void componentAdded(ContainerEvent e) {
        JTable table = SwingUtils.getDescendantOfType(JTable.class, chooser, "Enabled",     true);
        if (table != null) {
          for (MouseListener l : table.getMouseListeners()) {
            if (l == listener) {
              return;
            }
          }
          table.addMouseListener(listener);
        }
      }
    });
    chooser.showOpenDialog(null);
    System.exit(0);
  }
}
于 2013-07-12T18:10:14.257 回答
0

这是如何将删除键侦听器添加到您的JFileChooser

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.nio.file.Files;

public class JFileChooserUtilities
{
    public static void registerDeleteAction(JFileChooser fileChooser)
    {
        AbstractAction abstractAction = new AbstractAction()
        {
            public void actionPerformed(ActionEvent actionEvent)
            {
                JFileChooser jFileChooser = (JFileChooser) actionEvent.getSource();

                try
                {
                    File selectedFile = jFileChooser.getSelectedFile();

                    if (selectedFile != null)
                    {
                        int selectedAnswer = JOptionPane.showConfirmDialog(null, "Are you sure want to permanently delete this file?", "Confirm", JOptionPane.YES_NO_OPTION);

                        if (selectedAnswer == JOptionPane.YES_OPTION)
                        {
                            Files.delete(selectedFile.toPath());
                            jFileChooser.rescanCurrentDirectory();
                        }
                    }
                } catch (Exception exception)
                {
                    exception.printStackTrace();
                }
            }
        };

        fileChooser.getActionMap().put("delAction", abstractAction);

        fileChooser.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"), "delAction");
    }
}

代码改编自JavaTechnical的答案。

于 2016-05-14T13:06:55.710 回答