The purpose of my program is to do time-consuming file operations that are executed inside a for loop. That's why I would like the program to show the current operation through a text field. I don't know how to explain it in a simpler way. I can't post the whole program because it would be too long.
I can't find a way to update a JTextField field while a loop is running inside a method.
For example, in a loop like:
void Test() {
ArrayList<String> asList = new ArrayList<>();
// Load asList.
for (int jj=0; jj < asList.size(); jj++) {
// Miscellaneous instructions working on files.
TxtLog.setText(jj + " " + asList.get(jj));
}
}
The TxtLog field is never updated.
How do I get it to update while running the for loop?
EDIT: I solved with SwingWorker associated with a Thread.sleep!
javax.swing.Timerand give Swing a chance to update the display before setting the new text. Don’t use a loop for such task.JTextFieldto display the result of the Miscellaneous instructions working on files at the end of each loop iteration? If yes, then I think you also need to give the user time to read that result, no? Or does each miscellaneous instruction take a long time to complete? By the way, I suggest that you take the tour and read How to Ask.Test()method is not already running there (and it probably shouldn't be) then you can useSwingUtilities.invokeAndWait()to perform the update on the EDT and delay continuing until that has completed.