2

I want to sort an array inserted by the user. This part is ok already, what I'm having trouble is when you click the sort button, it gives some sort of a step by step inside a jtextarea, with some little time gap between each line.

There's where's my proble, I'm trying to put a Thread.sleep inside my for loop, for it to print one line then pause a little, but it isn't pausing at the right moment but before starting the sorting and prints it all at once.

public void bubbleSort(int[] arr) {
    int[] array_to_sort = arr;
    int[] initial_array = arr;
    int count = 1;
    String result = "";
    String result2 = "";
    for (int l = 0; l < initial_array.length; l++)
        result2 += arr[l] + " ";
    for (int i = array_to_sort.length; i >= 1; i--)
        for (int j = 1; j < i; j++)
            if (array_to_sort[j - 1] > array_to_sort[j]) {
                int aux = array_to_sort[j];
                array_to_sort[j] = array_to_sort[j - 1];
                array_to_sort[j - 1] = aux;
                for (int l = 0; l < array_to_sort.length; l++)
                    result += array_to_sort[l] + " ";
                Interface.jTextArea1.append(result + "\n"); // I'd like to pause after printing this line
                result = "";
                count++;
            }
}

Could someone enlighten me on how I could be doing this pause the right way?

  • 5
    One cannot use `Thread.sleep` from the UI thread (e.g. event callback) and expect the UI to update: it will "hang" until the operation completes. And one cannot update the UI - directly - from the non-UI thread (but there are ways to queue updates on the EDT). –  Dec 01 '12 at 18:49
  • @pst is calling SwingUtilities.invokeLater() a good solution, then ? (I'm asking, as I am not sure) – loloof64 Dec 01 '12 at 18:51
  • What @pst said. That would be expected behavior. See if you can trigger a redraw immediately before the sleep. – user Dec 01 '12 at 18:52
  • @LaurentBERNABE If the sort is running on a *worker thread*, then that is an appropriate mechanism to queue UI control updates. –  Dec 01 '12 at 18:52
  • You should not sleep on the EDT. That causes the GUI to freeze. Check this [post](http://stackoverflow.com/questions/13486803/thread-sleep1000-not-working-in-swing/13487292#13487292) – Extreme Coders Dec 01 '12 at 18:54
  • possible duplicate of [Program freezes during Thread.sleep() and with Timer](http://stackoverflow.com/questions/7816585/program-freezes-during-thread-sleep-and-with-timer) and soooo many others. This question is being asked at least every two weeks. – JB Nizet Dec 01 '12 at 19:12

1 Answers1

0

Interface.jTextArea1.append(result + "\n"); // I'd like to pause after printing this line

Do the following for(int i = 0; i < Short.MAX_VALUE;i++);
I mean just do an empty loop to simulate your delay. Although the proper solution would be to restructure your code to send the text to be printed in the EDT in intervals.

Cratylus
  • 52,998
  • 69
  • 209
  • 339