Reputation: 992
It's my goal to make a method I have written (that updates to a swing module) run with a 500ms delay in the loop. For example, here's roughly what my loop should look like:
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;
}
}
Edit: To better clarify my goals: My aim is to highlight the two numbers about to be swapped in a bubble sort by changing their color to red, waiting .5s then swapping them and returning their color to null(I have revised the code since to change the color to null, not to Color.WHITE as it was before). Sorry for the confusion.
Upvotes: 1
Views: 1216
Reputation: 44250
Use the javax.swing.Timer
class to execute events at a specified interval. This mechanism will ensure that the Swing components are modified in the event-dispatching thread.
Upvotes: 3