Reputation: 157
i've been struggling with the delay timer. how can i make the swapping visible to observer? and by putting color on selected bar while the swapping is processing? This is a selection sort by the way.
selectionSort2.java
/**
*
* @author Yuvinng
*/
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import javax.swing.Timer;
import java.awt.event.*;
public class SelectionSortPanel2 extends JPanel{
protected JButton selection;
private final int width=400,height=400;
private static Random generator;
private int[] list=new int[100];
private Timer timer;
public void selectionSort(int[] list)
{
int min;
int temp;
for(int index=0; index<list.length-1;index++)
{
min=index;
for(int scan=index+1;scan<list.length;scan++)
if(list[scan]<(list[min]))
min=scan;
temp=list[min];
list[min]=list[index];
list[index]=temp;
repaint();
}
}
private class swapper implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
selectionSort(list);
}
}
}
Upvotes: 1
Views: 663
Reputation: 205785
javax.swing.Timer
is a good choice, as it hides the thread used to wait and fires when it's time to draw. Just draw the result of one swap in the timer's actionPerformed()
method. You'll have to re-organize selectionSort()
so that it can run one step at a time. There's a related Timer
example here.
Upvotes: 2
Reputation: 11543
Instead of using a Timer which sorts your whole array every time it is invoked and without rewriting your sort method to only sort one element on each invocation you can do this.
When you use the Timer it actually execute in the same thread as repainting the guy, so if you do any sleep here the guy will not repaint.
Instead, change your swapper to be a Runnable, and create a new Thread with your swapper and start the thread.
Then, after swapping and calling repaint you can tell the swapping thread to sleep for a while Thread.sleep(delay).
JPanel does not clear itself between repaints, so you will only see columns grow, never get shorter. Either fix the paintComponent to clear the graphics or extend JComponent instead.
Hope that helps your progress.
Upvotes: 1