【问题标题】:How to wait on the FileChooser selection?如何等待 FileChooser 选择?
【发布时间】:2015-09-07 07:58:50
【问题描述】:

我想要做的是使用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 ");
        }

【问题讨论】:

标签: java path selection wait filechooser


【解决方案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();

希望这会有所帮助。

【讨论】:

  • 问题是,JFileChooser 已经在它自己的线程中运行。这就是panel.getPath() 不起作用的原因。因此,在不同的线程中处理文件选择很可能是最简单的方法。
  • 实际上 panel.getPath() 正在工作。程序只是不等待结果
  • @JürgenK。我知道它不会等待。这就是我所说的不工作。原因是不等待是因为我解释的线程问题。解决此问题的一种方法是创建事件侦听器。另一种方法(不推荐)是使用类似:while ((path = panel.getPath()) != null) {}。然而,这会带来比其价值更多的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多