0

我正在将语音识别组件与我现有的应用程序集成在一起。在我的应用程序中,我有一个 JTree 和 JTextPane。我已经为 jtextpane 编写了丢失焦点事件处理程序,并为 JTree 编写了选择事件处理程序。当焦点在 jtextpane 中然后在 jtree 中选择一个节点时,我可以看到在焦点丢失事件处理程序之前,执行了选择事件处理程序。我在焦点丢失事件处理程序中编写了 ThreadPoolExecutor,并向 ThreadPoolExecutor 添加了三个作业,我必须确保在执行选择处理程序之前我应该​​完成 ThradPoolExecutor 中的所有作业;为此我使用了倒计时。我已经阅读了许多类似的帖子,但我找不到如何确保在执行选择事件处理程序之前完成焦点丢失。一些帖子要求在 invokeLater 方法中运行选择事件处理程序代码。但这不是我的问题的解决方案,因为 ThreadPoolExecutor 在另一个线程中执行其代码。下面我记下了我想执行我的代码的顺序

  1. 在焦点丢失事件处理程序中将作业添加到 ThreadPoolExecutor
  2. 在失去焦点事件中阻塞 UI 线程并完成所有添加到 ThreadPoolExecutor 的作业。
  3. 执行选择事件处理程序。

下面是我的焦点处理程序的编写代码

public void focusLost(FocusEvent e)
  {

    if (ecaControl.isInitialized())
    {

      ecaControl.addStopRecordingJobToExecutor();

      ecaControl.addSaveJobToExecutor(this.currentMetaFileName != null ? this.currentMetaFileName : this.getName());

      ecaControl.addCloseJobToExecutor();

      co = new CountDownLatch(ecaControl.getExecutor().counter);
      ecaControl.getExecutor().setCountdownla(co);

      try
      {
        System.out.println("------- count before" + ecaControl.getExecutor().counter);
        co.await();

        ecaControl.getExecutor().setCountdownla(null);
      }
      catch (InterruptedException e1)
      {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      System.out.println("--------count after" + ecaControl.getExecutor().counter);
      try
      {
        System.out.println("The text is "
            + this.getStyledDocument().getText(0, getStyledDocument().getLength()));
      }
      catch (BadLocationException e1)
      {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

    }

  }
4

1 回答 1

0

如果选择事件仅与focusLost()事件一起发生,那么您应该调用awaitTermination()ThreadPoolExecutor然后在选择事件中调用invokeLater()方法。如果不是,那么最好的解决方案可能是事件调度程序。如果您将所有事件发送到事件分发器,它可以协调是否JTree需要等待,执行任何必要的线程,然后在适当的时间将事件重新分发到适当的组件。

于 2012-10-18T13:25:30.897 回答