我应该在哪里在 java swing 程序中使用 thread.sleep? [英] Where should I use thread.sleep in a java swing program?
问题描述
现在我已经编写了一个用于 Swing 程序的方法,该方法应该减慢调用它的方法的运行速度(通过 thread.sleep(x) ),而不是减慢刷新速度它只是导致整个程序在方法执行结束时挂起并刷新屏幕.
Right now I've programmed a method for use in a swing program that is supposed to slow down the speed the method it's called in is run (via thread.sleep(x) ) and instead of slowing down the speed of refresh it's just causing the whole program to hang and the screen to refresh at the end of the methods execution.
这是我的代码:
public final void doBubbleSort(String numbers[], JButton numButton[]){
for (int k = 0; k < numbers.length - 1; k++){
String str1 = "";
boolean isSorted = true;
for (int i = 1; i < numbers.length - k; i++){
if (Integer.parseInt(numbers[i]) < Integer.parseInt(numbers[i - 1]) ){
try{
String tempVariable = numbers[i];
numbers[i] = numbers[i - 1];
numbers[i - 1] = tempVariable;
isSorted = false;
str1 = numButton[i].getText();
numButton[i].setText(numButton[i-1].getText());
Thread.sleep(100);
}catch(Exception e){ System.err.println("Error: " +e.getMessage()); }
numButton[i-1].setText(str1);
}
}
if (isSorted)
break;
}
}
如果有人能告诉我应该把 thread.sleep() 放在哪里以延迟被交换的项目的显示,我将不胜感激.
If anyone can tell me where I should be putting thread.sleep() to make it delay the display of items being swapped I would be greatly appreciate it.
谢谢!
推荐答案
你不应该在事件调度线程中休眠.
You should never sleep in the event dispatch thread.
- 创建一个模型,(在您的情况下是一个列表)
- 创建一个视图(你的swing gui)
- 确保在模型更改后更新视图(例如通过添加侦听器)
- 创建一个单独的线程来定期更新模型(如果愿意,可以使用
Thread.sleep
) - 更改速度"时更改更新线程的睡眠时间
- Create a model, (in your case a list)
- Create a view (your swing gui)
- Make sure the view gets updated once the model changes (by adding a listener for instance)
- Create a separate thread that updates the model regularly (using
Thread.sleep
if you so like) - When changing "speed" change the sleep times for the updater-thread
你可能想看看 Timer
类(它提供了一个更好的界面来定期做事)或 Swing Workers.
You may want to have a look at the Timer
class (which provides a nicer interface for doing things at a regular interval) or the Swing Workers.
这篇关于我应该在哪里在 java swing 程序中使用 thread.sleep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!