我很难使用Swing worker来处理我的项目。它有两个程序,一个是logic (full program),另一个是GUI。我从GUI调用逻辑程序。由于它没有反应,我尝试使用Swing工作者。但即使我使用Swing工作者,它仍然没有反应。如果我运行该程序,它会显示GUI,但是如果我点击“开始”,则另一个程序会启动,它会变得无法响应。
这是GUI 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();
}
答案 0 :(得分:1)
因为它需要交互,所以在后台运行HelloWorld#main()
可能不方便。根据建议here,直接在LiveSpeechRecognizer
和publish()
中间结果中实例化SwingWorker
,以便在GUI中显示。您可以在Configuration
构造函数中指定SwingWorker
信息,也可以将其作为参数传递。概述基于示例here和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);
}
}