我和其他许多人一样,遇到并看到了这个问题无休止地张贴在这个论坛上的情况。不幸的是,从来没有回答过,也不是完全正确。
使用JFileChooser
时,有时会不规则地显示UI。这涵盖了Opening
和Saving
文件的时间。
例如,如果我有以下代码:
我尝试读取.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”未出现,因此问题很可能是在:
int resultat = fc.showOpenDialog(null);
值得注意的是,该程序不会关闭,但会继续运行而不会显示任何内容-没有错误等。在此先感谢您的帮助。
最佳答案
ShowOpenDialog()
停止执行线程,并等待用户输入。
一种选择是在AWT事件分配线程上不执行ShowOpenDialog()。
(使用调试器进行确认)
如果确实是您的情况-您可以尝试致电:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getFile();
}
});
甚至比仅使用SwingUtilities.invokeLater更好,请使用SwingWorker API。