我和其他许多人一样,无数次遇到并看到这个问题发布在这个论坛上;不幸的是,从来没有普遍或完全正确地回答过。
使用 JFileChooser
时,UI 有时会不规则地显示。这包括打开
和保存
文件。
例如,如果我有这段代码:
我尝试读取 .txt 并将每一行放入 Array
(allaNamn)。
public static void getFile() {
try {
System.out.println("1");
String aktuellMapp = System.getProperty("user.dir");
JFileChooser fc = new JFileChooser(aktuellMapp);
System.out.println("2");
int resultat = fc.showOpenDialog(null);
System.out.println("3");
if (resultat != JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "No file choosen.");
NamnProgram.main(null);
}
String fil = fc.getSelectedFile().getAbsolutePath();
BufferedReader inFil = new BufferedReader(new FileReader(fil));
String rad = inFil.readLine();
int counter = 0;
while (rad != null) {
rad = inFil.readLine();
counter++;
}
if (counter == 0) {
JOptionPane.showMessageDialog(null, "Textfil is empty");
}
BufferedReader skrivFil = new BufferedReader(new FileReader(fil));
allaNamn = new String[counter];
int antal = 0;
String sparaRad = skrivFil.readLine();
while (antal < counter) {
allaNamn[antal] = sparaRad;
sparaRad = skrivFil.readLine();
antal++;
}
//Closing
inFil.close();
skrivFil.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog (null, "Det misslyckades");
}
}
我试过调试这个,还有其他一些程序员;不幸的是没有任何成功。我在打印的方法中有一些 System.out.println()
:
1
2
"3" Does not show up, thus the problem is most likely in the:
int resultat = fc.showOpenDialog(null);
值得注意的是,该程序并没有关闭,而是继续运行而没有任何显示——没有错误或类似的东西。在此先感谢您的帮助。
最佳答案
ShowOpenDialog()
停止执行线程并等待用户输入。
一种选择是 ShowOpenDialog() 未在 AWT 事件调度线程上执行。
(使用调试器确认)
如果这确实是您的情况 - 您可以尝试调用:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getFile();
}
});
甚至比简单地使用 SwingUtilities.invokeLater 更好, 使用 SwingWorker API。
关于java - 带有 JFileChooser UI (?) 的 OS X 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616648/