2015-09-07 49 views
1

我想要做的就是使用FileChooser来选择路径。如何等待FileChooser选择?

的选择之后,路径应用下述实例使用。

我的问题是如何将强制所有等待的道路上,因为否则程序,而无需等待的只是运行。

//GUI 
    JFrame frame = new JFrame("Window"); 
    FileChooser panel = new FileChooser(); 

    frame.addWindowListener(
     new WindowAdapter() { 
     public void windowClosing(WindowEvent e) { 
      System.exit(0); 
      } 
     } 
    ); 
    frame.getContentPane().add(panel,"Center"); 
    frame.setSize(panel.getPreferredSize()); 
    frame.setVisible(true); 
    if(panel.getPath() == null){ 

    } 
    String path = panel.getPath(); 

    //some additional stuff that does not need any pathinformation 
    ....... 
    //next step calculation which runs without waiting 
    Calculation calc = new Calculation(); 
    calc.run(path); 

在此先感谢

附:
这是我的ActionListner包含

 if (result == JFileChooser.CANCEL_OPTION) { 
     System.out.println("Cancel was selected"); 
     } 
     else if (result == JFileChooser.APPROVE_OPTION) { 
     path = chooser.getSelectedFile().getAbsolutePath(); 
     System.out.println("getCurrentDirectory(): " 

       + chooser.getCurrentDirectory()); 
     System.out.println("getSelectedFile() : " 
       + chooser.getSelectedFile()); 
     } 
     else { 
      System.out.println("No Selection "); 
     } 
+2

你想阅读关于“模态”对话框。在这里看到,例如:https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html – GhostCat

+0

你的意思是这一个HTTPS:?//docs.oracle.com/javase/tutorial/uiswing/misc /modality.html –

+1

开始由具有看看[如何使用文件挑肥拣瘦(https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) – MadProgrammer

回答

-1

你可以使用一个更监听:

panel.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e){ 
     if (e.getActionCommand() == JFileChooser.APPROVE_OPTION) { 
      file = panel.getSelectedFile(); 
      // Do what you want with selected file 
     } else { 
      // When user pressed close or "X" in the corder. 
     } 
    } 
}); 

代替String path = panel.getPath();

希望这有助于。

+0

它是否使得另一个线程用于框架? –

+0

事情是,'JFileChooser'已经在它自己的线程中运行了。这就是为什么'panel.getPath()'不起作用。所以在不同的线程中处理文件选择很可能是最简单的方法。 –

+0

其实panel.getPath()正在工作。该程序不会等待结果 –