投稿で述べられているように、EDT(イベントディスパッチスレッド)をブロックしないことが重要です。以下の私の例では、実際の作業はEDTスレッドから開始され、ボタンをクリックしてActionListenerから開始されます。イベントディスパッチスレッドから分離されるように、別のスレッドでラップする必要があります。したがって、EDTはブロックされません。
また、別のスレッドからUIを更新する場合は、SwingUtilities.invokeLater()を実行する必要があることに注意してください。以下のコード例は、私の元のコードから少し簡略化されています。私は実際に複数のスレッドを使用して複数のタスクを並行して実行しており、それらの各スレッドでupdateProgress()が呼び出され、最新のステータスを追加してTextAreaを更新します。
完全なソースコードはここにあります:https ://github.com/mhisoft/rdpro/blob/master/src/main/java/org/mhisoft/rdpro/ui/ReproMainForm.java
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Don't block the EDT, wrap it in a seperate thread
DoItJobThread t = new DoItJobThread();
t.start();
}
});
class DoItJobThread extends Thread {
@Override
public void run() {
//do some task
// output the progress
updateProgress();
}
}
public void updateProgress(final String msg) {
//invokeLater()
//This method allows us to post a "job" to Swing, which it will then run
// on the event dispatch thread at its next convenience.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Here, we can safely update the GUI
// because we'll be called from the
// event dispatch thread
outputTextArea.append(msg);
outputTextArea.setCaretPosition(outputTextArea.getDocument().getLength());
//labelStatus.setText(msg);
}
});
}