Search code examples
javaswingswingworker

How can I call SwingWorker more than once?


I'm making an a very simple application to visualize sorting algorithms and I am using SwingWorker to paint the array multiple times per second.
If a user presses the 'reset' button, the array is re-shuffled and they can now choose which sorting algorithm to use again.

My problem is that after a reset, the execute() method no longer calls doInBackground(), even after instantiating a new SwingWorker.

How can I make it so that I can call execute() as many times as needed?

public void actionPerformed(ActionEvent event) {
    stopSort = false;
    doBubbleSort = false;
    doSelectionSort = false;
    doInsertionSort = false;
    if (event.getSource() == bubbleButton) {
        doBubbleSort = true;
        sort.execute();
    } else if (event.getSource() == selectionButton) {
        doSelectionSort = true;
        sort.execute();
    } else if (event.getSource() == insertionButton) {
        doInsertionSort = true;
        sort.execute();
    } else if (event.getSource() == resetButton) {
        reset();
        sort.execute();
    }
}
    public void reset() {
    displayArr.clearSwappedIndexes();
    displayArr.setFramesPainted(0);
    displayArr.setComplete(false);
    stopSort = true;
    shuffleArr(arr);
    sort = new Sorting(this, arr, displayArr);
}

Solution

  • If a user presses the 'reset' button, the array is re-shuffled and they can now choose which sorting algorithm to use again.

    else if (event.getSource() == resetButton) {
        reset();
        sort.execute();
    }
    

    Looks to me like you execute the SwingWorker immediately and don't give the user the chance to select the sorting algorithm. So when the user clicks the sorting button, the worker has already been used.

    I would think the code should be:

    else if (event.getSource() == resetButton) {
        reset();
        //sort.execute(); // remove
    }