简体   繁体   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

I have been reading introductory material on Concurrency in Java as well as multi-threading techniques specific to the Java Swing GUI. 我一直在阅读有关Java并发性的入门资料以及特定于Java Swing GUI的多线程技术。 I am currently unsure on what the best approach to use for my situation is. 我目前不确定哪种方法最适合我的情况。 My situation is the following: 我的情况如下:

I am developing a program where one piece of its functionality is to listen to a users speech using code from a voice recognition API while the user remains on that particular GUI screen. 我正在开发一个程序,其功能之一是使用语音识别API中的代码来收听用户语音,而用户仍停留在该特定GUI屏幕上。 Every word that the voice recognition detects will be added into a Java Swing Text Field on the UI in real-time. 语音识别检测到的每个单词都会实时添加到UI上的Java Swing文本字段中。 It is also very important that every word detected is added to the Text Field so it is important that the voice recognition thread runs until the user chooses to quit. 将检测到的每个单词都添加到“文本字段”也很重要,因此语音识别线程运行直到用户选择退出之前也很重要。

My code is currently contained within a method in a dedicated class. 我的代码当前包含在专用类的方法中。

public class VoiceRecognitionCore 
{

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

What would be the most efficient and safest way to have this thread constantly running and how can I give it access to the text field on the UI. 什么是使该线程持续运行的最有效和最安全的方法,以及如何赋予它访问UI上的文本字段的权限。

Thank you for your time 感谢您的时间

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

I will recommend you to have a look at SwingWorkers here 我建议您在这里看看SwingWorkers

From the pages of docs.oracle.com: 从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