[英]How can I slow down the execution of a specific method in java
我的目标是使我编写的方法(对swing模块的更新)在循环中以500ms的延迟运行。 例如,这里大致是我的循环应该是什么样子:
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]) ){
String tempVariable = numbers[i];
numbers[i] = numbers[i - 1];
numbers[i - 1] = tempVariable;
isSorted = false;
str1 = numButton[i].getText();
numButton[i].setBackground(Color.RED);
numButton[i-1].setBackground(Color.RED);
//Pause here for 500 ms
numButton[i].setText(numButton[i-1].getText());
numButton[i-1].setText(str1);
numButton[i].setBackground(null);
numButton[i-1].setBackground(null);
}
}
if (isSorted)
break;
}
}
编辑:为了更好地阐明我的目标:我的目标是通过将其颜色更改为红色,等待.5然后交换它们并将其颜色返回到null来突出显示要在冒泡排序中交换的两个数字(我已经修改了代码,因为将颜色更改为null,而不是之前的Color.WHITE)。 对困惑感到抱歉。
使用javax.swing.Timer
类以指定的时间间隔执行事件。 此机制将确保在事件派发线程中修改Swing组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.