问题描述
我正在尝试创建一个程序,该程序通过在每次排序循环时绘制一组代表数组的条形来可视化不同的排序算法.但是,当我从sorter类中设置数组时,该类又重新绘制了面板,似乎它只在第一次和最后一次迭代中调用paintComponent(),而未显示其间的步骤.
I'm trying to create a program which will visualize different sorting algorithms by drawing a set of bars representing an array along for each time the sort loops. However, when I set the array from within the sorter class which in turn repaints the panel, it seems that it only calls paintComponent() for the first and last iteration, not showing the steps in between.
以下是调用setNumberArray()方法的排序代码:
Here is the sort code which calls the setNumberArray() method:
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(".");
}
我知道它不会在两者之间重新绘制(有或没有延迟),因为它只打印一个".当我开始排序时.
I know it's not repainting in between (with or without the delay) because it only prints one "." when I start sorting.
推荐答案
立即忘记油漆,因为那样将无法解决您的问题.问题在于您正在EDT上调用Thread.sleep,EDT是主Swing线程,称为事件调度线程,这将使您的Swing应用进入睡眠状态(如您所知).而是使用Swing计时器来延迟,一切都会很好.要么这样做,要么让您的Thread.sleep在后台线程中进行.
Forget the paintImmediately as that won't solve your problem. The issue is that you're calling Thread.sleep on the EDT, the main Swing thread known as the event dispatch thread, and this will put your Swing app to sleep (as you're finding out). Instead use a Swing Timer for your delay and all will work well. Either that or do your Thread.sleep in a background thread.
这篇关于延迟循环重新绘制JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!