JFileChooser 不显示

JFileChooser not showing

关于 JFileChooser 的问题我已经有很长一段时间了,一直找不到帮助...问题是文件 window 没有显示。我试图找到这个问题的原因,并测试了以下内容:

public class Test {
   public static void main (String[] args) {   
   load();     
   }
   public static void load () {
      String folder = System.getProperty("user.dir");
      JFileChooser fc = new JFileChooser(folder);
      int resultat = fc.showOpenDialog(null);  
   }
}

当 运行 这段代码时,我确实得到 window 来显示。

但是,当我尝试这样做时:

public class Test {
    public static void main (String[] args) {   
    String input = JOptionPane.showInputDialog(null, "Make your choice!\n" +
                                                     "1. load file");      
    load();   

    }
}

window 没有显示,但是编程仍在 运行... 我不知道是什么导致了这个问题

这是一些代码,JFileChooser 需要一个子项,在本例中我使用 JDialog

JFileChooser fileChooser = new JFileChooser();
JDialog dialog = new JDialog();  

              fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
              int result = fileChooser.showOpenDialog(dialog);
              if (result == JFileChooser.APPROVE_OPTION) {
                  File selectedFile = fileChooser.getSelectedFile();
                  System.out.println("Selected file: " + selectedFile.getAbsolutePath());
              }else{
                  System.out.println("Cancelled");
              }

Java Mac 对事件调度线程中发生的 Swing 事物 非常挑剔。试试这个。

import java.awt.EventQueue;
import javax.swing.JFileChooser;

public class Test {
    private static int result;
    public static void main(String[] args) throws Exception {
        EventQueue.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                String folder = System.getProperty("user.dir");
                JFileChooser fc = new JFileChooser(folder);
                result = fc.showOpenDialog(null);
            }
        });
        System.out.println(result);
    }
}

InvokeAndWait 的文档是 here。但基本上,您将一个执行 Swing 操作的 Runnable 传递给它,它会在正确的线程中执行该操作。如果您不想等待,还有 InvokeLater。