sam*_*tob 5 java swing jfilechooser
我有一个关于JFileChooser的问题很长一段时间了,现在还没有找到帮助......问题是文件窗口没有显示出来.我试图找到这个问题的原因,我测试了以下内容:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
运行此代码时,我会看到要显示的窗口.
但是,当我尝试这个:
public class Test {
public static void main (String[] args) {
String input = JOptionPane.showInputDialog(null, "Make your choice!\n" +
"1. load file");
load();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,窗口没有显示,编程仍在运行...我不知道可能导致此问题的原因
Mac上的Java对事件调度线程中发生的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);
}
}
Run Code Online (Sandbox Code Playgroud)
InvokeAndWait的文档在这里.但基本上,你传递一个Runnable来做Swing的东西,它会在正确的线程中执行它.如果您不想等待,还有InvokeLater.