I have been reading introductory material on Concurrency in Java as well as multi-threading techniques specific to the 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. Every word that the voice recognition detects will be added into a Java Swing Text Field on the UI in real-time. 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.
Thank you for your time
I will recommend you to have a look at
SwingWorkershereFrom the pages of 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.