如何在按下批准或取消按钮时停止JFileChooser关闭?

Vol*_*kyi 4 java swing jfilechooser

我使用JFileChooser的方法showOpenDialog打开文件.

如何将ActionListener附加到"批准"按钮JFileChooser以及如何在单击"批准"按钮并完成侦听器后停止关闭此对话框.

现在我有:

public class MainFileChooser extends JFileChooser {

    private FileFilter plainFilter;

    public MainFileChooser() {

        super.setMultiSelectionEnabled(true);
        super.setAcceptAllFileFilterUsed(false);

        plainFilter = new PlainFilter();
        }

public int showOpenFileDialog() {
        ActionListener actionListener = null;
        // JDialog openFileDialog = super.createDialog(getParent());
        super.addActionListener(actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                File[] selectedFiles = MainFileChooser.this.getSelectedFiles();
                for (File file : selectedFiles) {
                    if (!file.exists()) {
                        JOptionPane.showMessageDialog(getParent(), file.getName() + " does not exist!",
                                "File is not found", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        super.setFileFilter(plainFilter);
        int userOption = super.showOpenDialog(MainFrame.getInstance().getMainFrame());
        super.removeActionListener(actionListener);
        return userOption;

    }
Run Code Online (Sandbox Code Playgroud)

方法showOpenFileDialog打开一个对话框,当我按下批准按钮actionListener被调用,如果文件不存在,则弹出错误消息.

但无论如何,JFileChooser正在关闭.如果文件不存在,我希望JFileChooser保持打开状态!

谢谢!

cam*_*ckr 5

您可以覆盖该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())
                {
                    super.approveSelection();
                }
                else
                    System.out.println("File doesn't exist");
            }
        };

        chooser.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println(e);
            }
        });

        chooser.setSelectedFile( new File("something.txt") );
        int returnVal = chooser.showSaveDialog(null);


        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
           System.out.println(chooser.getSelectedFile() );
        }

    }
}
Run Code Online (Sandbox Code Playgroud)