繁体   English   中英

在Java Swing GUI中使线程不断运行和更新文本框的最佳方法是什么

[英]What is the best way to have a thread a constantly running and updating a text box in Java Swing GUI

我一直在阅读有关Java并发性的入门资料以及特定于Java Swing GUI的多线程技术。 我目前不确定哪种方法最适合我的情况。 我的情况如下:

我正在开发一个程序,其功能之一是使用语音识别API中的代码来收听用户语音,而用户仍停留在该特定GUI屏幕上。 语音识别检测到的每个单词都会实时添加到UI上的Java Swing文本字段中。 将检测到的每个单词都添加到“文本字段”也很重要,因此语音识别线程运行直到用户选择退出之前也很重要。

我的代码当前包含在专用类的方法中。

public class VoiceRecognitionCore 
{

    public void RunVoiceRegonition() throws VoiceRecognitionException
    {
          //Voice recognition code here
    }
}

什么是使该线程持续运行的最有效和最安全的方法,以及如何赋予它访问UI上的文本字段的权限。

感谢您的时间

解决此问题的一种可能方法是在单独的线程上运行语音识别,然后在需要更新GUI时,只需利用SwingUtilities.invokeLater(Runnable runnable)即可更新GUI。

我建议您在这里看看SwingWorkers

从docs.oracle.com页面:

SwingWorker provides a number of communication and control features:

•The SwingWorker subclass can define a method, done, which is automatically invoked on the event dispatch thread when the background task is finished.

•SwingWorker implements java.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread. Other methods in this interface allow cancellation of the background task and discovering whether the background task has finished or been cancelled.

•The background task can provide intermediate results by invoking SwingWorker.publish, causing SwingWorker.process to be invoked from the event dispatch thread.

•The background task can define bound properties. Changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM