I am trying to make a sorting visualizer using Java Swing. I tested out my code involving bubble sort, but the GUI freezes for a few seconds before displaying the final result, which I think has something to do with Thread.sleep().
I was advised to use Swing timer instead, but I am not sure how to make that work. What can I try?
My code: MainWindow.java:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("Sorting Algorithm Visualizer");
frame.setBounds(100, 100, 1280, 720);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
newVisual = new Visual_window();
frame.add(newVisual);
SortingAlgorithms allAlgorithms = new SortingAlgorithms();
allAlgorithms.bubbleSort(newVisual, 100);
for(int i = 0; i < 100; i++) {
System.out.print(newVisual.getValue(i) + ", ");
}
}
Swap method in Visual_window
class which extends JPanel
and contains an unsorted array:
public void swap(int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
repaint();
//This is making the GUI not work and should be replaced with Swing timer equivalent.
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
BubbleSort in SortingAlgorithms
class:
public void bubbleSort(Visual_window array, int size) {
for(int i = 0; i < size - 1; i++) {
for(int j = 0; j < size - i - 1; j++) {
if(array.getValue(j) > array.getValue(j+1)) {
array.swap(j, j+1);
}
}
}
}
Although everything works if I remove the EventQueue.invokeLater
portion of the main function, but I am not sure if that is the right thing to do.