JFileChooser 以编程方式单击打开

JFileChooser click programmatically on open

我有以下代码来打开 JFilechooser

chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();

我想做的是以编程方式关闭此对话框。我看到了打开按钮,但我如何 "press" 以编程方式打开它?

这将模拟用户选择和打开文件:

JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(YourApplication.class.getName()).log(Level.SEVERE, null, ex);
        }
        chooser.setSelectedFile(new File("/your/file/path")));
        chooser.approveSelection();
    }
}).start();
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();

Thread.sleep(100) 很难看,但必须放在那里,否则调用 approveSelectionJFileChooser 尚未打开。