英文:
How can I call SwingWorker more than once?
问题
我正在制作一个非常简单的应用程序来可视化排序算法,我正在使用SwingWorker
来每秒多次绘制数组。如果用户按下"重置"按钮,数组将被重新洗牌,然后他们可以再次选择要使用的排序算法。
我的问题是,重置后,execute()
方法不再调用doInBackground()
,即使实例化了一个新的SwingWorker
。
我如何才能使execute()
可以根据需要调用多次?
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);
}
希望这对你有所帮助。如果你有其他问题,请随时提出。
英文:
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);
}
答案1
得分: 0
else if (event.getSource() == resetButton) {
reset();
//sort.execute(); // 移除
}
英文:
> 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论