I\'m making a sorting algorithm visualizer and i want the UI to update in real time to show how it works, step by step.
But the UI only updates when the sort() method is
Never sleep on the FX Application thread. That thread is responsible for rendering the UI, so by blocking it with Thread.sleep()
you prevent the UI from being rendered, as you have observed.
Instead, use the Animation API. A simple Timeline
should work here:
@FXML
public void sort() {
Timeline timeline = new Timeline();
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(500), e -> sort2()));
timeline.setCycleCount(rectList.size());
minHeight = rectHeight[0];
counter = 0;
minIndex = 0;
temp = 0;
timeline.play();
}
public void sort2() {
System.out.println("start sort");
System.out.println(minHeight);
System.out.println("find min");
for (int i = counter; i < (rectList.size()); i++) {
System.out.println("i= " + i);
if (rectHeight[i] < minHeight) {
minHeight = rectHeight[i];
System.out.println("minHeight= " + minHeight);
System.out.println("minIndex= " + i);
minIndex = i;
}
}
updateHeight();
}
public void updateHeight() {
temp = rectHeight[counter];
rectHeight[counter] = rectHeight[minIndex];
rectList.get(counter).setHeight(rectHeight[counter]);
rectHeight[minIndex] = temp;
rectList.get(minIndex).setHeight(temp);
counter++;
minHeight = rectHeight[counter];
minIndex = counter;
}