日期:2014-05-20  浏览次数:20750 次

弱弱的问下ldh911,approveSelection()没选文件是不会被触发的
昨天发了个帖:“高分雪地挥泪跪求获取JFileChooser弹出JDialog的按钮方法”
  弱弱的问下ldh911,approveSelection()方法没选文件或者没填路径是不会被触发的,这就没办法判断所选文件路径是否为空了,在线等。。。

------解决方案--------------------
确实出了个难题啊,供参考了:

Java code

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.reflect.*;

import javax.swing.*;
import javax.swing.plaf.basic.*;

public class TestJFileChooser extends JFileChooser {

    private boolean isSelected = false;

    public static void main(String[] args) {
        new TestJFileChooser().showOpenDialog(null);

    }

    @Override
    public int showDialog(Component parent, String approveButtonText) throws HeadlessException {
        if (this.ui instanceof BasicFileChooserUI) {
            try {
                Method method = BasicFileChooserUI.class.getDeclaredMethod("getApproveButton", JFileChooser.class);
                method.setAccessible(true);
                JButton btnApprove = (JButton) method.invoke(this.ui, this);
                System.out.println(btnApprove);
                btnApprove.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (TestJFileChooser.this.isSelected) {
                            TestJFileChooser.this.isSelected = false;
                        } else {
                            JOptionPane.showMessageDialog(null, "Please select a file.");
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return super.showDialog(parent, approveButtonText);
    }

    @Override
    public void setSelectedFile(File file) {
        this.isSelected = true;
        super.setSelectedFile(file);
    }

}