0
所以,我试图调用getFile()来打开一个JFileChooser。它第一次被调用,但不是第二次。我的JFileChooser在第二次使用时不起作用
我有一段时间(!完成)循环作为我的主菜单中的一个菜单,其中一个选项获取该文件并执行一些操作。它第一次正常工作,但第二次尝试从菜单执行时,它卡在if(returnVal == JFileChooser.APPROVE_OPTION)
。更奇怪的是,当我调试这条线时,它会多次工作。我也积极的对话框没有隐藏在第二次的地方。我能找到的唯一怀疑是事件派发线程中正在发生的事情,但这超出了我的理解水平。那么,我想我对JFileChoosers有些误解?
public void getFile()
throws FileNotFoundException, IOException
{
JFileChooser myChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("txt files", "txt");
myChooser.setFileFilter(filter);
int returnVal = myChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File myFile=myChooser.getSelectedFile();
this.myFile=myFile;
String tempFileName= myFile.getName();
fileName= tempFileName.substring(0, (tempFileName.length()-4));
System.out.println("File Picked: " +fileName);
this.fileName=fileName;
}
}
编辑:
好了,这是什么,再现了问题:
测试仪:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
throws FileNotFoundException, IOException
{
Scanner myScanner = new Scanner(System.in);
boolean done = false;
while (!done)
{ System.out.println("");
System.out.println("1 - GetFile");
System.out.println("2 - Exit");
int choice= Integer.parseInt(myScanner.nextLine());
if (choice ==1)
{ System.out.println("GetFile ");
Chooser myChooser=new Chooser();
myChooser.getFile();
System.out.println("done");
}
else if(choice ==2)
{ System.out.println("Good Bye"); done=true;}
else System.out.println("Invalid choice");
} while (!done);
System.exit(0);
}
}
计划:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
public class Chooser {
public void getFile()
throws FileNotFoundException, IOException
{
JFileChooser myChooser = new JFileChooser();
int returnVal = myChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("loop marker");
File myFile=myChooser.getSelectedFile();
String tempFileName= myFile.getName();
System.out.println("File Picked: " +tempFileName);
}
}
}
为了更好地帮助越早,张贴[MCVE]( http://stackoverflow.com/help/mcve)(最小完整可验证示例)。 – 2014-11-03 00:04:06
*“while(!done)loop作为我主菜单中的菜单”*现在我只是害怕。将一段断断续续的代码片段倾倒在我们身上,期待我们神奇地知道它是如何工作的,以及它的错在哪里就是神奇的想法。考虑提供一个[可运行的示例](https://stackoverflow.com/help/mcve),它可以证明你的问题。这将导致更少的混淆和更好的响应 – MadProgrammer 2014-11-03 00:04:53
这听起来像是你阻塞了事件调度线程。请参阅[并发中的Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) – MadProgrammer 2014-11-03 00:05:47