【发布时间】:2012-11-19 16:43:23
【问题描述】:
我想对用户插入的数组进行排序。这部分已经ok了 我遇到的问题是,当您单击排序按钮时,它会给出某种排序 在一个 jtextarea 中一步一步的,每行之间有一些小的时间间隔。
我的问题出在哪里,我正在尝试将 Thread.sleep 放入我的 for 循环中, 让它打印一行然后暂停一点,但它没有在正确的时刻暂停 但在开始排序并一次性打印之前。
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++;
}
}
有人能告诉我如何以正确的方式暂停吗?
【问题讨论】:
-
不能从 UI 线程(例如事件回调)使用
Thread.sleep并期望 UI 更新:它将“挂起”直到操作完成。并且不能直接从非 UI 线程更新 UI(但有一些方法可以在 EDT 上对更新进行排队)。 -
@pst 调用 SwingUtilities.invokeLater() 是一个很好的解决方案,然后呢? (我在问,因为我不确定)
-
@pst 说了什么。那将是预期的行为。看看你是否可以在睡眠前立即触发重绘。
-
@LaurentBERNABE 如果排序在 工作线程 上运行,那么这是一种对 UI 控件更新进行排队的适当机制。
-
你不应该睡在 EDT 上。这会导致 GUI 冻结。检查这个post
标签: java arrays sorting for-loop sleep