I'm working on an interactive sorting application in JavaFx:
- The numbers are represented by rectangles
- Every time two numbers are swapped the rectangles are swapped(using timeline - animation)
This is one of the sorting algorithms:
public class BubbleSort implements SortAlgorithm {
private volatile Boolean swaping;
public void sort(double[] array, CompareFunction compareFunction, Model model, Controller controller) {
Boolean ord;
int i;
double aux;
swaping = false;
do {
ord = true;
for (i = 0; i < array.length - 1; i++) {
if (compareFunction.compare(array[i], array[i + 1]) == false) {
while (swaping);
swaping = true;
aux = array[i];
array[i] = array[i + 1];
array[i + 1] = aux;
ord = false;
controller.swapRectangles(model.getRectangles().get(i), model.getRectangles().get(i + 1), this);
}
}
} while (ord == false);
}
public void setSwaping(Boolean swaping) {
this.swaping = swaping;
}
}
This is the prototype of the swapRectangles method:
public void swapRectangles(final Rectangle rectangle1, final Rectangle rectangle2, final BubbleSort bubbleSort)
And when timeline ends I udpate "swaping" value:
timeline2.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
setRectangleFill(rectangle2, Color.BLACK);
rectangle2.setX(rectangle1X);
bubbleSort.setSwaping(false);
}
});
The problem is that the "swaping" variable is never updating(the setSwaping method is never called).
Do you know why?
I think you update
swaping = true
insetSwaping
method but in sort method you again setswaping= false
before while loop execute. So I think your while loop is never executing since swaping is false. So you assuming that value is not being updating.Remove this line from your
sort
method:remove
;
and put your code inside while block.Running
while(swaping);
puts a hard pressure on processor, you are taking all it's power and give it to "do-nothing" loop. To solve that either add sleep inside:while(swaping) Thread.sleep(100);
or use more convenient synchronization mechanism like SemaphoreAlso if you run
sort
on UI thread you block it entirely, thussetOnFinished
will never get a chance to be run. You should runsort
on a separate thread:If you update UI from this thread, make sure you wrap UI calls into Platform.runLater.