反应迟钝的摇摆工人

Unresponsive swing worker

我很难使用 Swing worker 来处理我的项目。它有两个程序,一个是logic (full program),另一个是GUI。我正在从 GUI 调用逻辑程序。由于它没有响应,我尝试使用 Swing worker。但即使我使用 Swing worker,它仍然没有响应。如果我 运行 该程序,它会显示 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();
}

因为需要交互,可能后台运行HelloWorld#main()不方便。按照建议 , 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);
    }

}