I am having a hard time to use the Swing worker to work with my project. It has two programs, one is the logic (full program) and the other is GUI. I am calling the logic program from the GUI. And because of its unresponsiveness, I tried using Swing worker. But even if I use Swing worker, its still unresponsive. If I run the program, it displays the GUI, but if I click on start, the another program starts and it becomes unresponsive.
This the snippet of GUI program (full program):
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
state.setText("Listening");
System.out.println("Started Listening");
state.setBackground(new Color(51, 204, 0));
doRun(args);
}
});
public void doRun(String[] args) {
SwingWorker<Void, String> worker = new SwingWorker<Void, String>(){
@Override
protected Void doInBackground() throws Exception {
// Object to use from another program
HelloWorld obj = new HelloWorld();
obj.main(args);
return null;
}};
worker.execute();
}
Because it requires interaction, it may be inconvenient to run HelloWorld#main()
in the background. As suggested here, instantiate a LiveSpeechRecognizer
directly in your SwingWorker
and publish()
interim results for display in the GUI. You can specify Configuration
information in the SwingWorker
constructor or pass it as a parameter. In outline based on examples here and here,
private class BackgroundTask extends SwingWorker<Void, String> {
LiveSpeechRecognizer recognizer;
public BackgroundTask() {
statusLabel.setText((this.getState()).toString());
Configuration configuration = new Configuration();
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
recognizer = new LiveSpeechRecognizer(configuration);
recognizer.startRecognition(true);
}
@Override
protected Integer doInBackground() {
while (!isCancelled()) {
SpeechResult result = recognizer.getResult();
List<WordResult> list = result. getWords();
for (WordResult w : list) {
// get information to publish, e.g. getPronunciation()
// publish(getSpelling());
}
}
}
@Override
protected void process(java.util.List<String> messages) {
statusLabel.setText((this.getState()).toString());
for (String message : messages) {
textArea.append(message + "\n");
}
}
@Override
protected void done() {
recognizer.stopRecognition();
statusLabel.setText((this.getState()).toString() + " " + status);
stopButton.setEnabled(false);
startButton.setEnabled(true);
bar.setIndeterminate(false);
}
}