我正在尝试创建一个程序,通过在每次排序循环时绘制一组代表数组的条形图来可视化不同的排序算法。然而,当我从排序器类中设置数组并重新绘制面板时,它似乎只为第一次和最后一次迭代调用paintComponent(),而不显示之间的步骤。
以下是调用 setNumberArray() 方法的排序代码:
public void bubbleSort() {
int[] x = getNumberArray();
boolean doMore = true;
while (doMore) {
doMore = false;
for (int count = 0; count < x.length - 1; count++) {
if (x[count] > x[count+1]) {
int temp = x[count]; x[count] = x[count+1]; x[count+1] = temp;
doMore = true;
}
}
// Update the array
SorterGUI.getSorterPanel().setNumberArray(x);
// Pause
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(Sorter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
哪个调用:
public void setNumberArray(int[] numberArray) {
this.numberArray = numberArray;
repaint();
}
最后绘制条形:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int length = numberArray.length;
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.white);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setColor(Color.gray);
for(int count = 0; count < length; count++) {
g2d.fill3DRect((getWidth() / length) * (count + 1), 0,
getWidth() / length, getHeight() - (numberArray[count] * 3),
true);
playSound(numberArray[count]);
}
System.out.print(".");
}
我知道它不会在中间重新绘制(有或没有延迟),因为它只打印一个“。”当我开始排序时。
最佳答案
立即忘记油漆,因为这不能解决您的问题。问题是您在 EDT(称为事件调度线程的主 Swing 线程)上调用 Thread.sleep,这将使您的 Swing 应用程序进入休眠状态(正如您所发现的)。相反,使用 Swing Timer 来进行延迟,一切都会顺利进行。要么这样做,要么在后台线程中执行 Thread.sleep。
关于java - 在循环中延迟重新绘制 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4917383/