Whenever I use thread.sleep on my algorithm visualizer, my screen turns white. I have tried using a swing timer, but I couldn't do it since I am also trying to run the sorting loop. Other times when I tried to use swing timer, it ran the sorter completely and just infinitely called repaint(). I have also tried creating a new thread and putting thread.sleep onto there, but my screen turned white again. I'm not sure if a swing timer could work in this scenario.
public void drawPanel() {
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
System.out.println("repained");
}
};
timer = new Timer(1000, action);
timer.setRepeats(false);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.darkGray);
Graphics2D g2d = (Graphics2D) g;
int width = 10;
int x = 0;
Algorithims.HeapSort(listArr);
for (int i = 0; i < (screenWidth - 15) / width; i++) {
g2d.setPaint(Color.white);
g2d.fillRect(x, (screenHeight - listArr[i]) - 40, width, listArr[i]);
g2d.setPaint(Color.black);
g2d.drawRect(x, (screenHeight - listArr[i]) - 40, width, listArr[i]);
x += width;
}
}
public void swap(int i, int j) {
int temp = listArr[i];
listArr[i] = listArr[j];
listArr[j] = temp;
GUI gui = new GUI();
gui.drawPanel();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
listArr = shuffleRectangles();
JFrame frame = new JFrame();
GUI gui = new GUI();
frame.setTitle("Algorithim Visualizer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(screenWidth, screenHeight);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(gui);
}
Here is the the sorter from a different class:
public static void HeapSort(int[] array) {
GUI gui = new GUI();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] < array[j]) {
//swapping i and j
gui.swap(i, j);
}
}
}
}