我正在尝试创建一个程序,该程序将通过在每次排序循环时绘制一组代表数组的条来可视化不同的排序算法。但是,当我从排序器类中设置数组时,它会重新绘制面板,似乎它只在第一次和最后一次迭代中调用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(".");
}
我知道它不会在两者之间重新绘制(有或没有延迟),因为它只打印一个“。” 当我开始排序时。