Search code examples
javaswingjframejbuttonbubble-sort

Bubble Sort Simulation JButton coloring


Im trying to make a program that will help visualize the bubble sort algorithm. The script sorts the array correctly, however it does not allow the JFrame to open until it has finished. Is there a way to make it recolor all of the buttons before moving ahead with its sorting? Posted below is the class that handles the sorting and coloring currently.

public class SortStart {

    private JButton[] list;
    private int[] randomList;

    public SortStart(JButton[] list, int[] randomList){
        this.list = list;
        this.randomList = randomList;
    }

    public void run(){

        String str = "";
        int temp = 0;
        int k = 0;
        boolean swapped = true;

        //Sort the colors
        while(swapped){
            swapped = false;
            k ++;
            for(int i = 0; i < randomList.length - k; i ++){
                if(randomList[i] > randomList[i+1]){
                    temp = randomList[i];
                    randomList[i] = randomList[i+1];
                    randomList[i+1] = temp;
                    swapped = true;
                    for(int l = 0; l < randomList.length; l++){
                        System.out.print(randomList[l] + ", ");
                    }
                    System.out.println();
                    for(int j = 0; j < randomList.length; j++){
                        list[j].setBackground(new java.awt.Color(randomList[j],randomList[j],255)); 
                    }
                }
            }
        }
    }
}

Solution

  • SwingWorker can execute only once, instead make an instance of a Thread with a Runnable class using a PropertyChangeListener to reflect the changes in the view. You're using the view's thread to run your code so nothing else can execute (repaints) until finished. In your Runnable class you should define a PropertyChangeSupport object bound to the object been modified. And add the method addPropertyChangeListener (then define a PropertyChangeListener in your view), something like this:

    private PropertyChangeSupport mPcs =
        new PropertyChangeSupport(this);
    
    public void setMouthWidth(int mw) {
        int oldMouthWidth = mMouthWidth;
        mMouthWidth = mw;
        mPcs.firePropertyChange("mouthWidth", oldMouthWidth, mw); //the modification is "published"
    }
    
    public void
    addPropertyChangeListener(PropertyChangeListener listener) {
        mPcs.addPropertyChangeListener(listener);
    }
    
    public void
    removePropertyChangeListener(PropertyChangeListener listener) {
        mPcs.removePropertyChangeListener(listener);
    }