简体   繁体   中英

For loop & Thread.sleep

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM