As the post said it is important not to block the EDT (the Event Dispatch Thread). In my exmaple below the actual work starts from the EDT thread as it is from a button click ActionListener. I need to wrap it with a separate thread so it is separated from the Event Dispatch Thread. Thus the EDT is not blocked.
Also note you need to SwingUtilities.invokeLater() when update the UI from a separate Thread. The code example below is simplified a little from my original code. I am actually performing multiple tasks in parallel using multiple threads and in each of those thread the updateProgress() is called to update the TextArea by appending the latest status.
Full source code is here: 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);
}
});
}
Thread
for the loop. Now you are making sure it is executed on the EDT – Lacerate