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

时间:2014-04-15 19:32:22

标签: 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;

    }

方法showOpenFileDialog会弹出一个对话框,当我按下批准按钮actionListener时,如果文件不存在,则会弹出错误消息。

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

谢谢!

2 个答案:

答案 0 :(得分: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() );
        }

    }
}

答案 1 :(得分:0)

@Override
public void approveSelection(){
    for(File f : this.getSelectedFiles())
        if(!f.exists()) {
            //Show warning to user
            //if needed: cancelSelection();
            return;
        }              
    super.approveSelection();
}